如何在正则表达式中仅在特定字符串之间查找匹配?

4

我想在文本的特定位置找到多个匹配项。

例如,在以下文本中,我想要找到位于abcdxyz之间的所有a=.*;

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=.*;

1个回答

1

使用

(?<=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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接