【问题标题】:Regex multiline match only if string does not contain A but contains B仅当字符串不包含 A 但包含 B 时,正则表达式多行匹配
【发布时间】:2019-03-25 02:02:35
【问题描述】:

匹配一个多行字符串,其中一行不包含 A,但另一行包含 B。

难点在于文件包含多个这样的多行结构。

简单的部分是,如果文件包含无效组,正则表达式应该只返回真/假(找到/未找到)。

在我的示例中,我应该匹配一个 story(...),仅当它包含 bar,但不包含 foostuff..是可选的,可以是0行或多行随机词。

错误文件示例:

story(
  stuff..,
  foo,
  stuff..,
  bar,
)

story(
  stuff..,
  bar,
)         // <-- this file is bad because of this story

好文件的例子:

story(
  stuff..,
  foo,
  stuff..,
  bar,
)

story(
  stuff..,
  foo,
  stuff..,
  bar,
)

// no matches found here, the file is good

甚至可以用正则表达式做到这一点吗?如果是,它应该在这里工作:https://regex-golang.appspot.com/assets/html/index.html

【问题讨论】:

  • 如果将文本保存为字符串,它会返回一个列表,如果 foo=bar 存在,则结果将为空白,但如果不存在,它将显示查询内容。其实你规定qwe=raz必须在里面?
  • 好的。会看看。我上面的内容应该可以做之前需要做的事情。您可以只搜索结果数组以查看是否有任何值不是'',在这种情况下它将是一个坏文件
  • 所以:ok = (has foo, has bar) or (has foo) or (no foo, no bar);坏 =(没有 foo,有酒吧)?无论哪种情况,您都需要一个可以匹配“不包含 X”的正则表达式引擎。我不认为RE2可以。
  • 检查下面的答案。看看是否有效
  • 一个测试说明了很多 - youtube.com/watch?v=tEgovMqGG_8 确实,正则表达式确实匹配两者,但是一组在 () 内上演,这意味着它将被返回,而另一组并不意味着它不会被返回。看视频

标签: regex


【解决方案1】:

所以要演示一下 Python 中的一种肮脏解决方案,这应该可以做到

>>> string_1 = '''story(
  foo,
  stuff,
  bar,
)

story(
  stuff,
  bar,
)   '''




>>> string_2 = '''story(
  foo,
  stuff,
  bar,
)

story(
  foo,
  stupp,
  bar,
)'''





>>> def bad_file(string):
        import re
        matches = re.findall('story\([\S\s]*?foo[\S\s]*?bar[\S\s]*?\)|(story\([\S\s]*?bar[\S\s]*?\))', string)
        #matches = re.findall('story\([\S\s]*?foo[\S\s]*?bar[\S\s]*?\)|(story\([\S\s]*?\))', string)
        for i in range(len(matches)):
            if matches[i] != '':
                print('Bad File because of:\n')
                print(matches[i])
                print('\n'*2)
                print('List of bad matches:')
                return matches
            if i == (len(matches)) -1:
                print('Good File')


#Output
>>> bad_file(string_1)
Bad File


>>> bad_file(string_2)
Good File

【讨论】:

    猜你喜欢
    • 2012-01-04
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多