首页 > 解决方案 > 将文本匹配到多个组的正则表达式

问题描述

我正在尝试设置一个正则表达式来匹配文本,并且我希望一个特定的字符串与一个单独的组与文本的其余部分相匹配(如果它存在)。

例如,如果我的字符串是this is a test,我想this is a匹配第一组并test匹配第二组。我正在使用 python 正则表达式库。以下是我想要的结果的更多示例

在这些情况下,我在第二组中匹配的特定字符串是 test. 我不确定如何设置正则表达式以正确匹配这些特殊情况。

标签: pythonregex

解决方案


您可以尝试以下正则表达式:

^(this.*?)(test)?$

正则表达式的解释:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    this                     'this'
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  (                        group and capture to \2 (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    test                     'test'
--------------------------------------------------------------------------------
  )?                       end of \2 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \2)
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

推荐阅读