【问题标题】:How to Grep Search two occurrences of a character in a lookbetween如何在查找之间搜索两次出现的字符
【发布时间】:2021-04-29 02:01:55
【问题描述】:

每次我需要一些高级的东西时,我似乎都必须不断地重新学习 Regex 和 Grep 语法。这一次,即使使用 BBEDIT 的模式游乐场,我也无法解决这个问题。

我需要对 plist/XML 文件中一对标签之间的文本中任意位置出现的两个文字星号进行多行搜索。

我可以成功地构造一个lookbetween所以:

(?s)(?<=<array>).*?(?=</array>)

我尝试将其限制为仅匹配标签之间出现两个星号的情况:

(?s)(?<=<array>).*?[*]{2}.*?(?=</array>)
(?s)(?<=<array>).+[*]{2}.+(?=</array>)
(?s)(?<=<array>).+?[*]{2}.+?(?=</array>)

但他们一无所获。当我删除 {2} 时,我意识到我什至没有正确构建它来查找一个星号的出现。我尝试转义字符 /* 和 [/*] 但无济于事。

我如何匹配任何出现的 blah blah * blah blah * blah blah ?

【问题讨论】:

  • . 匹配任何字符,在模式中使用.*.+ 时不会限制任何内容。

标签: regex grep html-parsing textwrangler bbedit


【解决方案1】:

[*]{2} 表示两个星号必须是连续的。

(.*[*]){2} 是您要查找的内容 - 它包含两个星号,它们之间有任何内容。

但我们还需要确保正则表达式同时只测试一个标签闭包,因此我们需要使用((?!&lt;\/array&gt;).)* 来代替.*,以确保它不会消耗结束标签@987654326 @同时匹配.*

正则表达式可以写成:

(?s)(?<=<array>)(?:((?!<\/array>).)*?[*]){2}(?1)*

查看测试结果here

【讨论】:

    【解决方案2】:

    使用

    (?s)(?<=<array>)(?:(?:(?!<\/?array>)[^*])*[*]){2}.*?(?=</array>)
    

    proof

    说明

    NODE EXPLANATION
    (?s) set flags for this block (with . matching \n) (case-sensitive) (with ^ and $ matching normally) (matching whitespace and # normally)
    (?&lt;= look behind to see if there is:
      &lt;array&gt; '&lt;array&gt;'
    ) end of look-behind
    (?: group, but do not capture (2 times):
    (?: group, but do not capture (0 or more times (matching the most amount possible)):
    (?! look ahead to see if there is not:
    &lt;/?array&gt; &lt;/array&gt; or &lt;array&gt;
    ) end of look-ahead
    [^*] any character except: '*'
    )* end of grouping
    [*] any character of: '*'
    ){2} end of grouping
    .*? any character (0 or more times (matching the least amount possible))
    (?= look ahead to see if there is:
    &lt;/array&gt; '&lt;/array&gt;'
    ) end of look-ahead

    【讨论】:

    • 这是一个比我已经接受的 Hao Wu 的答案稍微不那么紧凑的表达,但它也很有效,我非常感谢您为逐个元素分解逻辑元素所付出的努力。如果我没看错的话,它比 Hao Wu 的效率略高,因为它会在测试两次出现之前分组并消除其中没有问号的任何标签对 [^*]。我说对了吗?
    • @brianfit 这个解决方案更精确,因为它不会重叠没有双星号的数组标签。由于经过调和的贪婪令牌,只有带有双星号的标签才会被匹配。它不是那么快,但使匹配更精确。参照。 Wu'smine
    猜你喜欢
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 2021-09-29
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2018-11-21
    相关资源
    最近更新 更多