RegEx to replace text between two hash-symbols, between two tags, but keep everything else

99封情书 提交于 2020-01-14 14:16:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!