正则表达式 python 用于匹配具有重叠匹配的确切字符数
例如,我有一个字符串t = "abftababcd"
我想匹配一个模式p=“abXX”
其中 X 是通配符并匹配任何字符。对于给定的 p 和 t 我想得到['abft', 'abab','abcd']
对于 p="XXab"
,预期输出是 ['ftab', 'abab']
现在我想匹配字符串 t 中的所有重叠匹配项。我尝试用
替换 X “ab\w{X 号}”
这不会给出重叠的匹配。所以我尝试将前瞻断言作为“ab(?=(\w{X 数}))”
那么这只会给我与模式“ab”的匹配。另外,如果 X 出现在字符串的开头 XXab
或中间 aXXXb
中,前瞻是否有效?
For example, I have a a stringt = "abftababcd"
I want to match a patternp= "abXX"
where X is a wild card and matches any character. For the given p and t I want to get['abft', 'abab','abcd']
For p="XXab"
the expected output is ['ftab', 'abab']
Now i want to match all the overlapping matches in string t. I have tried replacing X with"ab\w{no.of X}"
This doesn't give overlapping matches. So i tried lookahead assertion as"ab(?=(\w{no.of X}))"
Then this only gives me the matches with the pattern "ab". Also, does lookahead work if X is present in the beginning XXab
of the string or in the middleaXXXb
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以匹配
捕获组 1 包含每个匹配项,对于字符串来说,这些匹配项
是
"abft"
、"abab"
和"abcd"
。该表达式由一个正向先行组成,断言字符串中的当前位置后紧跟
'ab'
,后跟任意两个字符,这四个字符将保存到捕获组 1.将位置视为连续字符之间或字符串中第一个字符之前的位置。
演示
You can match
Capture group 1 contains each match, which for the string
are
"abft"
,"abab"
and"abcd"
.The expression consists of a positive lookahead that asserts that the current position in the string is followed immediately by
'ab'
followed by any two characters, with those four characters being saved to capture group 1.Think of positions as locations between successive characters or before the first character in the string.
Demo