加入两个正则表达式进行替换

时间:2016-09-30 10:01:03

标签: javascript regex

我有以下字符串

var query = `'4'="$USER$" AND '5'=""$USER$"" AND '6'="""$USER$""" AND '7'=""""$USER$"""""`;

两个几乎相似的正则表达式,一个用匹配引号替换匹配,另一个用三引号替换匹配:

var a = /(^|[^"])"(\$USER\$|\$TIME\$)"(?!")/g
var b = /(^|[^"])"""(\$USER\$|\$TIME\$)"""(?!")/g

我可以这样:

var firstQueryResult = query.replace(a, '$1$2');
var finalResult = firstQueryResult.replace(b, '$1"$2"') // replaces with additional one pair of quotes

但我想知道这是否可以在一个正则表达式中完成

1 个答案:

答案 0 :(得分:3)

正则表达式:

=\s*(?=("(")"|")\$)"+(\$USER\$|\$TIME\$)\1(?=[^"]|$)

Live demo

<强>解释

 =\s*           # Match `=` and any number of spaces
 (?=            # Start of a positive lookahead (pl:1)
     (              # Start of capturing group (1)
        "(")"       # Match 3 double quotes in a row (and capture one of them as 2nd CP)
     |              # OR
        "           # One single `"`
     )              # End of capturing group (1)
     \$             # That is followed by a `$`
 )              # End of positive lookahead (pl:1)
 "+             # Match any number of `"`
 (                  # Start of capturing group (2)
    \$USER\$        # Match `$USER$`
    |               # OR
    \$TIME\$        # Match `$TIME$`
 )              # End of capturing group (2)
 \1             # Followed by same number of quotes captured by 1st CP
 (?=            # Start of a positive lookahead (pl:2)
    [^"]            # Followed by a non-`"` character
    |               # OR
    $               # End of string
 )              # End of positive lookahead (pl:2)

JavaScript的:

string.replace(/=\s*(?=("(")"|")\$)"+(\$USER\$|\$TIME\$)\1(?=[^"]|$)/g, '=\2\3\2');

这也避免了不平衡的引号。