re.search() 只匹配第一次出现 [英] re.search() only matches the first occurrence

查看:254
本文介绍了re.search() 只匹配第一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配模式:

<--标题标题-->一些正文

以下只匹配第一次出现:

string1 = """<-- 选项 1 -->好文<--最后的东西-->列出所有的这文本"""regex = re.compile(r"<--([\w\s]+)-->([\s\S]*?)(?=\n<--|$)")m = regex.search(string1)打印 m.groups()

结果:

(' 选项 1 ', '\n不错的文字')

然而,使用pythex似乎可以正常工作.

我做错了什么?

解决方案

Re.search 只匹配字符串中的第一个匹配项.您想要 finditerfindall.

<块引用>

研究

扫描字符串以查找正则表达式模式产生匹配的第一个位置,并返回相应的 MatchObject 实例.如果字符串中没有位置与模式匹配,则返回 None;请注意,这与在字符串中的某个点找到零长度匹配不同.

Finditer 返回目标字符串中所有位置的匹配对象,产生一个迭代器,而 findall 返回所有匹配的子字符串.

<预><代码>>>>进口重新>>>re.findall('a', 'ababababa')['a', 'a', 'a', 'a', 'a']>>>x = list(re.finditer('a', 'ababababa'))>>>X[<_sre.SRE_Match 对象;跨度=(0, 1),匹配='a'>,<_sre.SRE_Match 对象;跨度=(2, 3), match='a'>,<_sre.SRE_Match 对象;span=(4, 5), match='a'>,<_sre.SRE_Match 对象;跨度=(6, 7),匹配='a'>,<_sre.SRE_Match 对象;span=(8, 9), match='a'>]>>>x[0].group()'一种'

I'm trying to match the pattern:

<--Header Title-->
some body text

The following only matches the first occurrence:

string1 = """<-- Option 1 -->
Nice text
<--Final stuff-->
Listing all
of
the
text
"""

regex = re.compile(r"<--([\w\s]+)-->([\s\S]*?)(?=\n<--|$)") 
m = regex.search(string1)
print m.groups()

Which results in:

(' Option 1 ', '\nNice text')

However, it seems to work fine using pythex.

What am I doing wrong?

解决方案

Re.search only matches the first occurrence within the string. You want finditer or findall.

re.search

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

Finditer returns match objects for all locations within the target string, yielding an iterator, while findall returns the substrings for all matches.

>>> import re
>>> re.findall('a', 'ababababa')
['a', 'a', 'a', 'a', 'a']

>>> x = list(re.finditer('a', 'ababababa'))
>>> x
[<_sre.SRE_Match object; span=(0, 1), match='a'>,
 <_sre.SRE_Match object; span=(2, 3), match='a'>,
 <_sre.SRE_Match object; span=(4, 5), match='a'>,
 <_sre.SRE_Match object; span=(6, 7), match='a'>,
 <_sre.SRE_Match object; span=(8, 9), match='a'>]
>>> x[0].group()
'a'

这篇关于re.search() 只匹配第一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆