regex - 仅当它们在特定字符串之间时,如何在正则表达式中查找匹配项?

标签 regex

我试图在文本的特定位置找到多个匹配项。
例如,在下面的文本中,我想找到所有 a=.*;之间abcdxyz

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/

相关文章:

javascript - 将字符串中的 '\' 替换为 '-'

regex - 在 stringr 中拆分一个大写跟随小写的字符串

java - 使用 Scanner 读取文件

php - 在正则表达式中,如何仅替换相同字符串的某些实例?

Javascript:使用正则表达式搜索连续的任意四位数字

python - 正则表达式 Python

javascript - 带字符转义的字符范围

c++ - vim 或 gcc 无法解释的行为

r - stringr - 删除多个空格,但保留换行符 (\in,\r)

regex - 搜索多个连续字符并替换为单个字符,同时排除某些字符