我希望匹配所有内容但没有引用的字符串.
我可以匹配所有引用的字符串:/(("([^"\\]|\\.)*")|('([^'\\]|\\.)*'))/
所以我试图匹配所有但没有带引号的字符串:/[^(("([^"\\]|\\.)*")|('([^'\\]|\\.)*'))]/但它不起作用.
我只想使用正则表达式,因为我想要替换它并希望在它之后获取引用的文本.
string.replace(regex, function(a, b, c) {
// return after a lot of operations
});
Run Code Online (Sandbox Code Playgroud)
引用的字符串对我来说就像这个"坏字符串"或这个"酷字符串"
所以,如果我输入:
he\'re is "watever o\"k" efre 'dder\'4rdr'?
Run Code Online (Sandbox Code Playgroud)
它应该输出这个匹配:
["he\'re is ", " efre ", "?"]
Run Code Online (Sandbox Code Playgroud)
而且我不想替换他们.
我知道我的问题非常困难但并非不可能!没有什么是不可能的.
谢谢
这可以做到,但有点复杂.
result = subject.match(/(?:(?=(?:(?:\\.|"(?:\\.|[^"\\])*"|[^\\'"])*'(?:\\.|"(?:\\.|[^"'\\])*"|[^\\'])*')*(?:\\.|"(?:\\.|[^"\\])*"|[^\\'])*$)(?=(?:(?:\\.|'(?:\\.|[^'\\])*'|[^\\'"])*"(?:\\.|'(?:\\.|[^'"\\])*'|[^\\"])*")*(?:\\.|'(?:\\.|[^'\\])*'|[^\\"])*$)(?:\\.|[^\\'"]))+/g);
Run Code Online (Sandbox Code Playgroud)
将返回
, he said.
, she replied.
, he reminded her.
,
Run Code Online (Sandbox Code Playgroud)
从此字符串开始(为了清楚起见,添加了换行符并删除了引号):
"Hello", he said. "What's up, \"doc\"?", she replied.
'I need a 12" crash cymbal', he reminded her.
"2\" by 4 inches", 'Back\"\'slashes \\ are OK!'
Run Code Online (Sandbox Code Playgroud)
说明:(有点像,有点令人难以置信)
打破正则表达式:
(?:
(?= # Assert even number of (relevant) single quotes, looking ahead:
(?:
(?:\\.|"(?:\\.|[^"\\])*"|[^\\'"])*
'
(?:\\.|"(?:\\.|[^"'\\])*"|[^\\'])*
'
)*
(?:\\.|"(?:\\.|[^"\\])*"|[^\\'])*
$
)
(?= # Assert even number of (relevant) double quotes, looking ahead:
(?:
(?:\\.|'(?:\\.|[^'\\])*'|[^\\'"])*
"
(?:\\.|'(?:\\.|[^'"\\])*'|[^\\"])*
"
)*
(?:\\.|'(?:\\.|[^'\\])*'|[^\\"])*
$
)
(?:\\.|[^\\'"]) # Match text between quoted sections
)+
Run Code Online (Sandbox Code Playgroud)
首先,您可以看到有两个相似的部分.这两个前瞻断言都确保前面的字符串中有偶数个单/双引号,而忽略了相反类型的转义引号和引号.我将用单引号部分显示它:
(?= # Assert that the following can be matched:
(?: # Match this group:
(?: # Match either:
\\. # an escaped character
| # or
"(?:\\.|[^"\\])*" # a double-quoted string
| # or
[^\\'"] # any character except backslashes or quotes
)* # any number of times.
' # Then match a single quote
(?:\\.|"(?:\\.|[^"'\\])*"|[^\\'])*' # Repeat once to ensure even number,
# (but don't allow single quotes within nested double-quoted strings)
)* # Repeat any number of times including zero
(?:\\.|"(?:\\.|[^"\\])*"|[^\\'])* # Then match the same until...
$ # ... end of string.
) # End of lookahead assertion.
Run Code Online (Sandbox Code Playgroud)
双引号部分的作用相同.
然后,在这两个断言成功的字符串中的每个位置,正则表达式的下一部分实际上尝试匹配某些东西:
(?: # Match either
\\. # an escaped character
| # or
[^\\'"] # any character except backslash, single or double quote
) # End of non-capturing group
Run Code Online (Sandbox Code Playgroud)
整个过程重复一次或多次,尽可能多次.该/g修改可以确保我们得到了所有比赛的的字符串中.
| 归档时间: |
|
| 查看次数: |
522 次 |
| 最近记录: |