Python正则表达式(Re.Escape,Re.Findall);如何:查找子字符串+字符串中子字符串以外的字符数?

2024-04-24 08:10:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是一个简单的问题。我正在学习如何使用正则表达式,在字符串上执行特定任务时遇到了困难

例如:

示例_string=“;一,一;二,二;三,三;四,四”

所需的#u输出=[“一,o”,“二,t”,“三,t”,“四,f”]#列表输出正常

通过以下步骤,我可以得到[“一”、“二”、“三”]:

def findStringsInMiddle(a, b, text): 
    return re.findall(re.escape(a)+"(.*?)"+re.escape(b),text)

desired_output = findStringsInMiddle('; ' , ',' , example_string)

但是我很难弄清楚如何正确地配置它来获取逗号+空格+任何我想要的字符类型

有什么建议吗

谢谢


Tags: 字符串textre示例列表outputstringreturn
3条回答

这里有一个解决方案:

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']

通过包含右侧分隔符并附加可选的(?:\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*.)?-一个可选的非捕获组,匹配0+空格的1次或0次出现,然后匹配任何字符

注意,我添加了re.S标志以使.也匹配换行符

见Efull Python snippet below

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']

相关问题 更多 >