【问题标题】:RegExp: Last occurence of pattern that occurs before another patternRegEx:在另一个模式之前出现的最后一次出现的模式
【发布时间】:2013-06-07 15:04:40
【问题描述】:

我想采用在另一个文本模式之前最后出现的文本模式。

例如我有这样的文字:

code 4ab6-7b5
Another lorem ipsum
Random commentary.

code f6ee-304
Lorem ipsum text 
Dummy text

code: ebf6-649
Other random text
id-x: 7662dd41-29b5-9646-a4bc-1f6e16e8095e

code: abcd-ebf
Random text
id-x: 7662dd41-29b5-9646-a4bc-1f6e16e8095e

我想取最后一个出现在id-x 之前的code(这意味着我想获取代码ebf6-649

如何使用正则表达式做到这一点?

【问题讨论】:

  • 我用的是git bash,所以我认为是unix引擎
  • 通过“使用正则表达式”,我认为您的意思是“使用 git-bash”? (我的意思是,你为什么关心答案是否恰好使用正则表达式?)
  • @JasonSwartz 我实际上认为这个问题的先前版本非常好,并且会给你更多有用的答案。这种有限形式的解决方案可能会在您的实际输入中产生误报。
  • Other random text 行可以有哪些字符?

标签: regex git-bash


【解决方案1】:

如果您的正则表达式支持lookaheads,您可以使用这样的解决方案

^code:[ ]([0-9a-f-]+)(?:(?!^code:[ ])[\s\S])*id-x

您可以在捕获号1 中找到您的结果。

它是如何工作的?

^code:[ ]           # match "code: " at the beginning of a line, the square 
                    # brackets are just to aid readability. I recommend always
                    # using them for literal spaces.

(                   # capturing group 1, your key
  [0-9a-f-]+        # match one or more hex-digits or hyphens
)                   # end of group 1

(?:                 # start a non-capturing group; each "instance" of this group
                    # will match a single arbitrary character that does not start
                    # a new "code: " (hence this cannot go beyond the current
                    # block)

  (?!               # negative lookahead; this does not consume any characters,
                    # but causes the pattern to fail, if its subpattern could
                    # match here

    ^code:[ ]       # match the beginning of a new block (i.e. "code: " at the
                    # beginning of another line

  )                 # end of negative lookahead, if we've reached the beginning
                    # of a new block, this will cause the non-capturing group to
                    # fail. otherwise just ignore this.

  [\s\S]            # match one arbitrary character
)*                  # end of non-capturing group, repeat 0 or more times
id-x                # match "id-x" literally

(?:(?!stopword)[\s\S])* 模式让您尽可能匹配,而不会超出stopword 的另一次出现。

请注意,您可能必须对^ 使用某种形式的多行模式来匹配行首。如果您的random text 包含open:,则^ 对于避免误报很重要。

Working demo(使用 Ruby 的正则表达式,因为我不确定你最终会使用哪一个)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-25
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    相关资源
    最近更新 更多