正则表达式需要有两个条件结束条件

2024-10-01 02:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个正则表达式来处理不同的终端条件,我的想法是这样的,但它不起作用

re.findall(r'(?<=tests\[")(.*)((?="\])|(?=:)', input_string])

输入格式如下:

tests["Status code: " +responseCode.code] = responseCode.code === 200;
tests["Schema validator GetTerminalInitEventForHarewareIds"] = tv4.validate(data, schema);

Tags: re终端inputstringschema格式statuscode
1条回答
网友
1楼 · 发布于 2024-10-01 02:35:15

说明

^tests\["(.*?)(?::\s*"\s*[^\]]|"\])

Regular expression visualization

此正则表达式将执行以下操作:

  • 要求字符串以tests["开头
  • 匹配第一个双引号内的子字符串

示例

现场演示

https://regex101.com/r/oE9lL6/3

示例文本

tests["Status code: " +responseCode.code] = responseCode.code === 200;
tests["Schema validator GetTerminalInitEventForHarewareIds"] = tv4.validate(data, schema);

样本匹配

  • 捕获组0获取整个匹配
  • 捕获组1只获取第一个引号中的值。
    • 如果值以: "结尾,后跟非],则不包括:和尾随文本
    • 如果该值以: "]结尾,则:和尾随空格将包括在内
MATCH 1
1.  [7-18]  `Status code`

MATCH 2
1.  [78-129]    `Schema validator GetTerminalInitEventForHarewareIds`

MATCH 3
1.  [169-224]   `Schema validator GetTerminalInitEventForHarewareIds: `

解释

NODE                     EXPLANATION
                                   
  ^                        the beginning of a "line"
                                   
  tests                    'tests'
                                   
  \[                       '['
                                   
  "                        '"'
                                   
  (                        group and capture to \1:
                                   
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
                                   
  )                        end of \1
                                   
  (?:                      group, but do not capture:
                                   
    :                        ':'
                                   
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
                                   
    "                        '"'
                                   
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
                                   
    [^\]]                    any character except: '\]'
                                   
   |                        OR
                                   
    "                        '"'
                                   
    \]                       ']'
                                   
  )                        end of grouping
                                   

相关问题 更多 >