Regex substring one mismatch in any location of string

孤人 提交于 2020-01-15 07:08:07

问题


Can someone explain why the code below returns an empty list:

>>> import re
>>> m = re.findall("(SS){e<=1}", "PSSZ")
>>> m
[]

I am trying to find the total number of occurrences of SS (and incorporating the possibility of up to one mismatch) within PSSZ.

I saw a similar example of code here: Search for string allowing for one mismatch in any location of the string


回答1:


You need to remove e<= chars present inside the range quantifier. Range quantifier must be of ,

  • {n} . Repeats the previous token n number of times.
  • {min,max} Repeats the previous token from min to max times.

It would be,

m = re.findall("(SS){1}", "PSSZ")

or

m = re.findall(r'SS','PSSZ')

Update:

>>> re.findall(r'(?=(S.|.S))', 'PSSZ')
['PS', 'SS', 'SZ']


来源:https://stackoverflow.com/questions/31364367/regex-substring-one-mismatch-in-any-location-of-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!