python中的正则表达式(^ string \ s \ w +)

时间:2016-11-03 05:41:00

标签: regex python-2.7

我想知道如何使用正则表达式进行搜索。

这是我的代码

import re
data = "python one test code"
p = re.compile("^python\s\w+")

结果

print(p.findall(data))    
['python one']

我想得到的结果如下

print(p.findall(data))
['python one test code']

我可以获得以上结果,如下所示

p = re.compile("^python\s\w+\s\w+\s\w+")

但我不想重复“\ s \ w +”,如“^ python \ s \ w + \ s \ w + \ s \ w +”

如何在“\ s \ w +”中使用*或+来获得结果?

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

^python(?:\s\w+)+

Explanation

  1. ^python字符串以python
  2. 开头
  3. ?:不会捕获()组
  4. \s\w+将匹配空格和直接字
  5. (?:\s\w+)+外部加号将匹配所有出现的no.3,其中+表示一个或多个

答案 1 :(得分:0)

您可以尝试以下

p = re.compile("^python[\w\s]*")
相关问题