RegEx replace text between two hash characters, between two tags, but keep everything else

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 additional 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 is between two hash characters and inside a cfquery tag, which may or may not have attributes.

I am using grepWin for replacement.

+3


source to share


2 answers


Another solution with regex:

You can use the following:

(#[^#><]*#)(?=[^>]*<\/cfquery>)

      



And replace with:

<cfqueryparam value="$1" />

      

See DEMO

+6


source


Strategy

You can use it awk

quite simply. In pseudocode, we'll try the following:

look for occurrence of cfquery
substitute as desired
until /cfquery is found

      

Script



This results in the following script:

in_query {
    $0 = gensub(/(#[^#]+#)/, "<cfqueryparam value=\"\\1\" />", "g", $0)
}
/<cfquery.*>/ {
    in_query = 1
}
/<\/ *cfquery.*>/ {
    in_query = ""
}
{
    print $0
}

      

Using

awk -f script.awk file

      

+2


source







All Articles