如何在正则表达式中查找所有匹配项

2024-05-19 08:36:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我的表达式能够处理一个事件,但如果给定多个事件,它将捕获整个部分。你知道吗

我的正则表达式是

[=:]\s*[\"\']?(.*=_ash)[\"\']?

我同时尝试了regex.findallsearch 我得到了整个部分时,多个出现在那里。你知道吗

如果我的正则表达式本身有问题,我是否需要设置任何标志来搜索多个事件。你知道吗

前三条线正常,但

sample_string = 'asdfanksdfkjasdf_ash'

sample_str = "asdfasdfasdf_ash"

sample_st = assdfvb/23+sdf_ash

sample_s : 'assdfvb/23+sdf_ash'

sample = {'sample' : { 'hi' : 'asdfasdf+/asdf+_ash' , 'hello' : 'asdfasf+/asdf+v_ash' }} 

我只需要有价值的部分


Tags: samplesearchstring表达式标志事件regexsdf
2条回答

模式的问题是.*。你知道吗

默认情况下,regex引擎是贪婪的,.*消耗尽可能多的资源。要更改此行为,可以使用lazy quantifier。添加额外的“?在.*?中的“使它尽可能少地重复。你知道吗

此外,如果值不是以"_ash"结尾,请检查引用文本中的引号,如果没有引用,则检查空格:

正则表达式:

[=:]\s*(?:(["'])((?:(?!\1).)*_ash)\1|(\S*_ash)(?!\S))

regex101 Demo

  • (["'])捕获组1中的引号
  • (?:(?!\1).)*匹配组1中捕获的引号以外的任何字符
  • \1匹配结束引号(与开始引号相同)
  • \S*对于不带引号的文本,匹配除空格以外的任何内容
  • (?!\S)检查此处的值结尾

如果值在引号中,则在.group(2)中捕获;如果值不在引号中,则在.group(3)中捕获。你知道吗

代码:

#python 2.7.10
import re

text = """sample = {'sample' : { 'hi' : 'asdfasdf+/asdf+_ash' , 'hello' : 'asdfasf+/asdf+v_ash' }}"""
n = 0

pattern = re.compile( r'[=:]\s*(?:(["\'])((?:(?!\1).)*_ash)\1|(\S*_ash))')

#loop all matches
for match in pattern.finditer(text):
    n += 1
    print '\nMatch #%s:' % n

    #Show groups 2 and 3 captures
    for i in range(2,4):
        print 'Group %s - [%s:%s]:  %s' % (i, match.start(i), match.end(i), match.group(i))

ideone Demo

我想你需要把正则表达式改成:

[=:]\s*['"]?([^\s\'\"=:]*?_ash)['"]?

[Regex Demo]

相关问题 更多 >

    热门问题