python - 将文本匹配到多个组的正则表达式
问题描述
我正在尝试设置一个正则表达式来匹配文本,并且我希望一个特定的字符串与一个单独的组与文本的其余部分相匹配(如果它存在)。
例如,如果我的字符串是this is a test
,我想this is a
匹配第一组并test
匹配第二组。我正在使用 python 正则表达式库。以下是我想要的结果的更多示例
this is a test
- 第 1 组:this is a
,第 2 组:test
one day at a time
- 第 1 组:one day at a time
,第 2 组:one day test is
- 第 1 组:one day
,第 2 组:test
testing, 1,2,3
- 没有匹配this is not a drill
- 第 1 组:this is not a drill
,第 2 组:
在这些情况下,我在第二组中匹配的特定字符串是 test. 我不确定如何设置正则表达式以正确匹配这些特殊情况。
解决方案
您可以尝试以下正则表达式:
^(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
推荐阅读
- python - 为熊猫中的单个值创建单独的列
- sql - 根据 Bigquery 计划查询中的日期动态更改 FROM 表名
- reactjs - 在 React Hooks 中输入文本时,antd Select Option 不呈现
- blazor-webassembly - Blazor WASM TargetFrameworks 网络标准 2.1 和 net5.0
- javascript - 单击按钮时切换脚本执行
- android - 无法加载 github.com 的信息
- assembly - 二叉搜索树插入程序集 x86
- css - @media 查询中的 CSS 字体大小在旋转后不会变回
- javascript - 谷歌表格隐藏网址
- configuration - 这个“编辑小部件”视图(适用于 iOS 14 小部件)的名称是什么?我该如何定义这样的东西?