我是使用regex的新手,非常感谢您的帮助。我必须用以下格式的字符串来解析文件(主要区别是第二个字符串中间有一个额外的"-"字符串:
-
Abc_p123 abc_ghi_data
或
-
Abc_de*_p123 abc_ghi_data
我可以写一个正则表达式来分别匹配第一个和第二个字符串:
data_lst = re.findall('([a-zA-Z0-9]+_pd{3})s.*_data.*', content, re.IGNORECASE)
data_lst = re.findall('([a-zA-Z0-9]+_[a-zA-Z]+_pd{3})s.*_data.*', content, re.IGNORECASE)
有人能指导如何组合两个findallregex,使其与两个字符串一起工作吗。通过将第二个findall语句附加到第一个列表中,我仍然可以创建一个组合的单个列表。但是,我确信有一种方法可以在一个findallregex语句中处理它。我试过了*"在中间,但是,这会产生错误。
请告知。谢谢,
你非常接近:
([a-zA-Z0-9]+(?:_[a-zA-Z]+*)?_pd{3})s.*_data.*
这里是重要的部分:
(?:_[a-zA-Z]+*)?
上面写着:可以选择匹配一个下划线,后面跟着无限的a-z,后面跟着一个星号。
https://regex101.com/r/5XCsPK/1
您可以尝试
([a-zA-Z0-9]+(_[a-zA-Z]+)?_pd{3})s.*_data.*
我用(_[a-zA-Z]+)?
替换了_[a-zA-Z]+
,使其成为可选的。
如果你不想要额外的捕获组,可以像这样添加?:
:(?:_[a-zA-Z]+)?
演示:https://regex101.com/r/5xynlx/2
使用
([a-zA-Z0-9]+(?:_[a-zA-Z0-9*]+)?_pd{3})s.*_data
查看验证
解释
--------------------------------------------------------------------------------
( group and capture to 1:
--------------------------------------------------------------------------------
[a-zA-Z0-9]+ any character of: 'a' to 'z', 'A' to
'Z', '0' to '9' (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
_ '_'
--------------------------------------------------------------------------------
[a-zA-Z0-9*]+ any character of: 'a' to 'z', 'A' to
'Z', '0' to '9', '*' (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
_p '_p'
--------------------------------------------------------------------------------
d{3} digits (0-9) (3 times)
--------------------------------------------------------------------------------
) end of 1
--------------------------------------------------------------------------------
s whitespace (n, r, t, f, and " ")
--------------------------------------------------------------------------------
.* any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
_data '_data'