正则表达式如果第一个匹配,则显示第二个匹配的结果

时间:2019-01-28 16:21:09

标签: regex

我正在尝试构造一个正则表达式模式,如果第一个模式被匹配,它将返回第二个模式的结果。我正在尝试使用特殊的if / then / else构造,但似乎如果if语句为true,则结果是每个单个字符,而不是then模式。我该如何重写此正则表达式,以便仅在then模式为true的情况下才返回if匹配项?在这种情况下,不需要else。我指的是这个article。最终目标是将其与rg一起使用。

编辑:更新正则表达式,因为findme永远不会紧跟pattern,而且我理解我的逻辑错误。如果使用if / then逻辑确实存在findme,我仍在尝试匹配pattern

我当前的正则表达式为(?(pattern)findme),尽管在这种情况下我真的不喜欢使用超前行。 Regex101显示匹配所有内容:

enter image description here

示例文本(包含patternfindme)。有两个findme。示例文本中的换行符是有意的:

Sed ut perspiciatis unde omnis iste natus error 
sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto
beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit pattern aut fugit, sed quia consequuntur magni dolores eos findme qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed
quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam,
quis nostrum exercitationem findme ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequ
atur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

1 个答案:

答案 0 :(得分:0)

看一下解释:

(?(?=pattern)findme)

If Clause (?(?=pattern)findme)
Evaluate the condition below and proceed accordingly
Positive Lookahead (?=pattern)
Assert that the Regex below matches
pattern matches the characters pattern literally (case sensitive)
If condition is met, match the following regex findme
findme matches the characters findme literally (case sensitive)

尝试一下:

(?<=pattern)findme

here