python - 正则表达式 : matching and grouping a variable number of space separated words

标签 python regex

我有一个字符串:

"foo hello world baz 33"

foobaz 之间的部分将是一些空格分隔的单词(一个或多个)。我想将这个字符串与一个 re 匹配,该 re 将对每个单词进行分组:

>>> re.match(r'foo (<some re here>) baz (\d+)', "foo hello world baz 33").groups() 
('hello', 'world', '33')

re 应该是灵活的,这样它就可以在没有单词的情况下工作:

>>> re.match(r'(<some re here>)', "hello world").groups() 
('hello', 'world')

我正在尝试使用 ([\w+\s])+ 进行变体,但我无法捕获动态确定的组数。这可能吗?

最佳答案

re.match 在字符串的开头返回结果。请改用 re.search
.*? 返回两个单词/表达式之间的最短匹配(。表示任何内容,* 表示出现 0 次或多次,? 表示最短匹配)。

import re
my_str = "foo hello world baz 33"
my_pattern = r'foo\s(.*?)\sbaz'
p = re.search(my_pattern,my_str,re.I)
result =  p.group(1).split()
print result

['hello', 'world']

编辑:

如果缺少 foo 或 baz,并且您需要返回整个字符串,请使用 if-else:

if p is not None:
    result = p.group(1).split()
else:
    result = my_str  

为什么 ? 在模式中:
假设单词 baz 出现多次:

my_str =  "foo hello world baz 33 there is another baz"  

使用 pattern = 'foo\s(.*)\sbaz' 将匹配(最长且贪婪):

'hello world baz 33 there is another'

然而,使用 pattern = 'foo\s(.*?)\sbaz' 将返回最短匹配:

'hello world'

关于python - 正则表达式 : matching and grouping a variable number of space separated words,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33416263/

相关文章:

python - 加载本地主机时 Django Nonrel 中的管道错误

python - Pandas 中的数据透视表/反转表(但不完全是)

python - 使用 ImageField 对 Django ModelForm 进行单元测试,测试显示无效表单

java - 如何使用替换/正则表达式替换字符串中的两个字符?

regex - 在 Vim 的新选项卡中显示所有匹配的 grep 结果

python - psycopg2 无法执行多个查询

python - 检查通过元素的 + 和 - 的任意组合,数组总和是否为零

regex - 使用awk或sed将文件的特定区域输出到另一个文件?

python - 简单的python正则表达式找不到字(在空格字符内)

java - 从文本文件中提取某些值(姓名、电子邮件、电话号码)