gpt4 book ai didi

javascript - 将两个正则表达式合并为一个以进行替换

转载 作者:行者123 更新时间:2023-11-28 18:21:30 26 4
gpt4 key购买 nike

我有以下字符串

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

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

最佳答案

正则表达式:

=\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');

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

关于javascript - 将两个正则表达式合并为一个以进行替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39788842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com