问题
So I need to replace #var# and #var2# with <cfqueryparam value="#var#" />
and <cfqueryparam value="#var2#" />
. However, this should only happen when #var# is wrapped inside <cfquery></cfquery>
.
As an extra criteria, the cfquery-tag will contain text before and after the hash-symbols. This is an example:
<cfquery datasource="#tablename#">
SELECT * FROM table WHERE name = #var#, somethingelse = #var2#;
</cfquery>
I need a regex that only matches 'test' when it's between two hash-symbols and inside a cfquery-tag that may or may not have attributes.
I'm using grepWin to do the replacement.
回答1:
Another solution with regex:
You can use the following to match:
(#[^#><]*#)(?=[^>]*<\/cfquery>)
And replace with:
<cfqueryparam value="$1" />
See DEMO
回答2:
Strategy
You could use awk
it's simple enough. In pseudo code we will try the following:
look for occurrence of cfquery
substitute as desired
until /cfquery is found
Script
This results in following script:
in_query {
$0 = gensub(/(#[^#]+#)/, "<cfqueryparam value=\"\\1\" />", "g", $0)
}
/<cfquery.*>/ {
in_query = 1
}
/<\/ *cfquery.*>/ {
in_query = ""
}
{
print $0
}
Usage
awk -f script.awk file
来源:https://stackoverflow.com/questions/30506640/regex-to-replace-text-between-two-hash-symbols-between-two-tags-but-keep-every