【问题标题】:Move backwards in regex pattern during next search在下一次搜索期间以正则表达式模式向后移动
【发布时间】:2017-03-09 19:26:15
【问题描述】:

我有以下模式的数据:

abc@1.0 name='abc'
abc@1.0 dep= {
"this",
"that",
}
abc@1.0 someInfo = "blahblah"
abc@2.0 name='abc'
abc@2.0 dep= {
"this",
"that",
}
abc@2.0 someInfo = "blahblah"
abc@3.0 name='abc'
abc@3.0 dep= {
"this",
"that",
}
abc@3.0 someInfo = "blahblah"

目标是查找每个组件@版本的所有记录(例如 abc@1.0)。我找到了多种解决此问题的方法,并且它们运行良好。但是,在此过程中,我无法使用一种特定的正则表达式逻辑来解决此问题。

这是我尝试过的:

(1) 删除所有换行符

(2) 正则表达式模式(abc@.+?)(abc@|$)

问题是这只会获得替代记录,因为我们在正则表达式模式中使用了下一个“abc@”。

我正在尝试在执行下一次正则表达式搜索之前找到一种方法在字符串中移回。即我想获得所有记录,而不仅仅是替代。

请注意,我不是在寻找解决方案 - 我已经解决了这个问题。我想知道如何在执行下一次正则表达式搜索之前返回字符串。

编辑:

感谢@sln,我正在寻找的正则表达式模式:(?s)abc@(?:(?!abc@).)*

【问题讨论】:

  • 记录从哪里开始和结束?
  • 使用(?s)abc@(?:(?!abc@).)*之类的东西对记录进行分区。
  • @sln 谢谢,你的第二条评论正是我想要的。

标签: python regex string regular-language


【解决方案1】:

虽然你说,你已经有了一个解决方案,这是我想出的。通常,您只能使用backtracking control verb 向后退,但这里并不需要这样做。


你有两个可能的值星座,一个是"...",一个是{...},而后者包括其他几个值。此外,您只想拥有特定针的值。看看这段代码(demo on ideone.comregex part on regex101.com
import re

string = your_string_here

def getResults(needle=None):
    """ Analyze the outer structure """
    # outer regex
    rx = re.compile(re.escape(needle) + r'''    # escape the needle to look for
        \s*
        (?P<key>\w+)                            # the key
        \s*=\s*
        (?:
            (['"])(?P<value>.+?(?!\\))\2        # a single value
            |
            \{(?P<values>[^{}]+)\}              # multiple values in {}
        )''', re.VERBOSE)

    def parseInnerValues(values=None):
        """ Parse the inner values """
        # inner regex
        rxi = re.compile(r'''(["'])(.+?)(?<!\\)\1''')
        return [m.group(2) for m in rxi.finditer(values)]

    def getValues(match=None):
        """ Decide """
        if match.group('values'):
            return parseInnerValues(match.group('values'))
        else:
            return match.group('value')

    matches = {match.group('key') : getValues(match)
                for match in rx.finditer(string)
                }
    return matches

print(getResults('abc@2.0'))
# {'dep': ['this', 'that'], 'someInfo': 'blahblah', 'name': 'abc'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-28
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多