Python-Regex(Re.Escape,Re.Findall);如何:在字符串中的子字符串之外查找子字符串+多个字符?

问题描述 投票:2回答:4

这可能是一个简单的问题。我正在学习如何使用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时遇到麻烦。

有什么建议吗?

谢谢!

python regex string parsing findall
4个回答
2
投票

您可以通过包含右定界符并附加可选的(?:\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标志以使.也匹配换行符。

请参阅full 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']

3
投票

您可以设置完整模式(从分号到逗号后的第二个字母,并标记要提取的组:

>>> s =  "; One, one; Two, two; Three, three; Four, four"
>>> re.findall(r"; (.*?,.{2})", s)
['One, o', 'Two, t', 'Three, t', 'Four, f']

1
投票

这里有一个解决方案:

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

1
投票
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']
© www.soinside.com 2019 - 2024. All rights reserved.