我试图在文本的特定位置找到多个匹配项。
例如,在下面的文本中,我想找到所有 a=.*;
之间abcd
和 xyz
abcd
a=1;
some text
a=2; some text
b=3;
a=4;
xyz
a=5;
a=6;
所以它应该只匹配: a=1;
a=2;
a=4;
并且不匹配:a=5;
a=6;
到目前为止,我尝试了以下正则表达式:(?<=abcd\n)(.*)(?=\nxyz)
返回 'abcd'
之间的字符串和 'xyz'
,但我没有成功匹配所有 a=.*;
里面
最佳答案
用
(?<=abcd[\s\S]*)a=.*;(?=[\s\S]*xyz)
见 JS regex proof .说明
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
abcd 'abcd'
--------------------------------------------------------------------------------
[\s\S]* any character of: whitespace (\n, \r,
\t, \f, and " "), non-whitespace (all
but \n, \r, \t, \f, and " ") (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
a= 'a='
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
; ';'
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
[\s\S]* any character of: whitespace (\n, \r,
\t, \f, and " "), non-whitespace (all
but \n, \r, \t, \f, and " ") (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
xyz 'xyz'
--------------------------------------------------------------------------------
) end of look-ahead
关于regex - 仅当它们在特定字符串之间时,如何在正则表达式中查找匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69523600/