Home  >  Q&A  >  body text

关于python正则表达式中函数findall的用法?

1.我的目标是匹配一个地址 ex:123 xuancheng anhui China
2.我给的正则表达式为:r'd+(s+[a-zA-Z]+)+s*'
代码如下:

pattern = r'\d+(\s+[a-zA-Z]+)+\s*'
basestr = '123  xuancheng china '
m1 = re.findall(pattern, basestr)
if m1 is not None:
    print m1
得到的结果为 [' china']

这个是以圆括号的内容进行匹配的,我想要配置的是整句话,如何改造呢?
除了以下这个用法
pattern_2 = r'(d+(s+[a-zA-Z]+)+s*)'
返回
[('123 xuancheng china ', ' china')]
使用search 函数能得到想要的结果
m2 = re.search(pattern, basestr)
print m2.group()
得到:
123 xuancheng china

伊谢尔伦伊谢尔伦2716 days ago1093

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:21:31

    r'\d+(?:\s+[a-zA-Z]+)+\s*'

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:21:31

    This is simple and crude, please modify it yourself.

    Modify it again and it will look like this

    New strings provided are also available.

    reply
    0
  • Cancelreply