[英]Python regular expression ignoring the first character from a string
I have a python regular expression where in I see that it is ignoring the first character from the matched string.我有一个 python 正则表达式,我看到它忽略了匹配字符串中的第一个字符。 when i try the same regex using pythex.org i could see it working as expected.当我使用 pythex.org 尝试相同的正则表达式时,我可以看到它按预期工作。 can someone help me why i;m seeing this issue?有人可以帮我为什么我看到这个问题吗?
import re
def expandTrafficItemList(a):
skip_list = []
pat = re.compile(r'([A-Za-z]+)(\d+)-[A-Za-z]+(\d+)')
if a:
c = a.split(',')
print(c)
for items in c:
print(items) # here it is not matching the string TRF instead it takes only RF
b = pat.search(items, re.I)
print(b.group(0))
a = "'TRF1-TRF25','RAW1-RAW4'"
expandTrafficItemList(a)
output: output:
["'TRF1-TRF25'", "'RAW1-RAW4'"]
'TRF1-TRF25'
RF1-TRF25
'RAW1-RAW4'
AW1-RAW4
You're placing the flag in the wrong place.你把旗帜放在错误的地方。 When you put re.I
in the search
method, you're inadvertently actually changing the start pos for the search
.当您将re.I
放入search
方法时,您实际上是在不经意间更改了search
的起始位置。 Take a look at re
documentation for more on that.查看re
文档以了解更多信息。 The re.I
flag actually goes in the compile
method. re.I
标志实际上在compile
方法中。 Also, you don't seem to need it as you use [A-Za-z]
, which covers upper and lower case values, but in case you need it for more flags in the future, put it in the compile
.此外,您似乎不需要它,因为您使用[A-Za-z]
,它涵盖了大写和小写值,但如果您将来需要它用于更多标志,请将它放在compile
中。
Your fixed code:您的固定代码:
import re
def expandTrafficItemList(a):
skip_list = []
pat = re.compile(r'([A-Za-z]+)(\d+)-[A-Za-z]+(\d+)', flags=re.I)
if a:
c = a.split(',')
print(c)
for items in c:
print(items)
b = pat.search(items)
print(b.group(0))
a = "'TRF1-TRF25','RAW1-RAW4'"
expandTrafficItemList(a)
output: output:
["'TRF1-TRF25'", "'RAW1-RAW4'"]
'TRF1-TRF25'
TRF1-TRF25
'RAW1-RAW4'
RAW1-RAW4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.