如果您的正则表达式支持前瞻,您可以使用这样的解决方案
^code:[ ]([0-9a-f-]+)(?:(?!^code:[ ])[\s\S])*id-x
您可以在 capture number 中找到您的结果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
.
请注意,您可能必须使用某种形式的多行模式^
来匹配行首。如果您的contains ^
,避免误报很重要。random text
open:
工作演示(使用 Ruby 的正则表达式风格,因为我不确定您最终将使用哪一个)