这可能是一个简单的问题。我正在学习如何使用Regex,但在执行字符串上的特定任务时遇到了麻烦。
例如:
example_string =“;一,一;二,二;三,三;四,四”]
期望输出= [“一个,o”,“两个,t”,“三个,t”,“四个,f”]#列表输出是可以的
通过以下操作,我可以获得[“一个”,“两个”,“三个”]:
def findStringsInMiddle(a, b, text):
return re.findall(re.escape(a)+"(.*?)"+re.escape(b),text)
desired_output = findStringsInMiddle('; ' , ',' , example_string)
但是我在弄清楚如何正确配置它以获取我也想要的逗号+空格+ any_type_of_character时遇到麻烦。
有什么建议吗?
谢谢!
您可以通过包含右定界符并附加可选的(?:\s*.)?
组来稍微重新组织模式:
def findStringsInMiddle(a, b, text):
return re.findall(re.escape(a)+"(.*?"+re.escape(b) + r"(?:\s*.)?)",text, flags=re.S)
该模式看起来像;(.*?,(?:\s*.)?)
(请参见the regex demo),并且将匹配:
;
-左定界符(.*?,(?:\s*.)?)
-组1:.*?
-零个或多个字符,尽可能少的字符],
-逗号(?:\s*.)?
-可选的非捕获组,它匹配1个或0个出现的0+空白,然后是任何字符。注意,我也添加了re.S
标志以使.
也匹配换行符。
import re
example_string = "; One, one; Two, two; Three, three; Four, four"
desired_output = ["One, o", "Two, t", "Three, t", "Four, f"] #list output is OK
def findStringsInMiddle(a, b, text):
return re.findall(re.escape(a)+"(.*?"+re.escape(b) + r"(?:\s*.)?)",text, flags=re.S)
desired_output = findStringsInMiddle('; ' , ',' , example_string)
print(desired_output)
# => ['One, o', 'Two, t', 'Three, t', 'Four, f']
您可以设置完整模式(从分号到逗号后的第二个字母,并标记要提取的组:
>>> s = "; One, one; Two, two; Three, three; Four, four"
>>> re.findall(r"; (.*?,.{2})", s)
['One, o', 'Two, t', 'Three, t', 'Four, f']
这里有一个解决方案:
example_string = "; One, one; Two, two; Three, three; Four, four"
def findStringsInMiddle(text):
return re.findall("; (.+?, [a-z])",text)
desired_output = findStringsInMiddle(example_string)
desired_output
输出:
['One, o', 'Two, t', 'Three, t', 'Four, f']
import re
example_string = "; One, one; Two, two; Three, three; Four, four"
pattern = re.compile(r";\s" # The search string must start with a semoicolon and then a space character
r"([A-Z][a-z]+,\s.?)" # Here is the capturing group, containing first a capital letter,
# some lowercase letters
# and finally a comma, space and zero or one characters
)
print(re.findall(pattern,
example_string
)
)
输出:
['One, o', 'Two, t', 'Three, t', 'Four, f']