regex - 正则表达式一致分组
问题描述
我从RegEx 修改了这个相当混乱的正则表达式,用于捕获重复模式 https://regex101.com/r/Trdwks/1
(([0-9]{1,2}h)[ ]*([0-9]{1,2}min):\s*|([0-9]{1,2}h)():\s*|()([0-9]{1,2}min):\s*)((?:.(?!(\dh\s\d{1,2}min|\dh|\d{1,2}min)))+)
这个想法是它匹配这个字符串,对小时、分钟和描述进行分组。
1h 30min: Title
- Description Line 1
3h: SECOND TITLE
- Description Line 1
- Description Line 2
- Description Line 3
1h 14min: Title
- another Great one 42min: Title - Great Movie
- Description Line 2
- Description Line 3
并产生以下结果:
Match 1:
"1h 30min: Title
- Description Line 1"
Group 1: "1h"
Group 2: "30min"
Group 3: "Title
- Description Line 1"
Match 2:
"3h: SECOND TITLE
- Description Line 1
- Description Line 2
- Description Line 3"
Group 1: "1h"
Group 2: ""
Group 3: "SECOND TITLE
- Description Line 1
- Description Line 2
- Description Line 3"
Match 3:
"1h 14min: Title
- another Great one"
Group 1: "1h"
Group 2: "14min"
Group 3: "Title
- another Great one"
Match 4:
"42min: Title - Great Movie
- Description Line 2
- Description Line 3"
Group 1: ""
Group 2: "42min"
Group 3: "Title - Great Movie
- Description Line 2
- Description Line 3"
我很难让分组保持一致,因为可能只有几个小时,只有几分钟,或两者兼而有之。所以上面的正则表达式可能会在group 3
or group 6
. 有没有办法修复初始或语句中的分组以在每个场景中返回一致的分组?
解决方案
这个解决方案只需要支持前瞻断言。
(?s)(?=[^:]*\d[^:]*:)(([0-9]{1,2}h)?[ ]*([0-9]{1,2}min)?:\s*)((?:.(?!(\dh\s\d{1,2}min|\dh|\d{1,2}min)))+)
https://regex101.com/r/gz4r9g/1
展开
(?s)
(?= [^:]* \d [^:]* : )
( # (1 start)
( [0-9]{1,2} h )? # (2)
[ ]*
( [0-9]{1,2} min )? # (3)
: \s*
) # (1 end)
( # (4 start)
(?:
.
(?!
( # (5 start)
\d h \s \d{1,2} min
| \d h
| \d{1,2} min
) # (5 end)
)
)+
) # (4 end)
该解决方案只需要支持分支重置。
(?s)(?|([0-9]{1,2}h)[ ]*([0-9]{1,2}min)|([0-9]{1,2}h)()|()([0-9]{1,2}min)):\s*((?:.(?!(\dh\s\d{1,2}min|\dh|\d{1,2}min)))+)
https://regex101.com/r/pyACdi/1
展开
(?s)
(?|
( [0-9]{1,2} h ) # (1)
[ ]*
( [0-9]{1,2} min ) # (2)
| ( [0-9]{1,2} h ) # (1)
( ) # (2)
| ( ) # (1)
( [0-9]{1,2} min ) # (2)
)
: \s*
( # (3 start)
(?:
.
(?!
( # (4 start)
\d h \s \d{1,2} min
| \d h
| \d{1,2} min
) # (4 end)
)
)+
) # (3 end)
推荐阅读
- python - 无法创建文件错误,文件不存在
- mysql - SQL - 如何从过去 5 年中选择日期以包括最早年份的 1 月 1 日
- javascript - 带有自定义字体系列的 Syncfusion JavaScript (ES5) 导出图表
- for-loop - 是否可以在 Kotlin 中编写一个 for 循环,在其中我可以在迭代期间将索引更改为我想要的任何值?
- oracle - “ORA-00925:缺少 INTO 关键字”与 sqlalchemy
- rust - 定义表示不透明 C 结构的 Rust 类型的交叉编译安全方法,其大小在编译时已知
- python - 如何使用列表中的数据在 Kivy 的滚动视图中添加一行?Python
- python - 机器人在用户点击反应后发送消息,当他删除他的反应时(python,discord)
- algorithm - 给定一个语法,如何为不完整的字符串找到有效的 AST?
- angular10 - Angular 10 根据组中的控件动态生成输入