正则表达式,匹配任何未包含在

Regular expression, match anything not enclosed in

给定字符串 foobarbarbarfoobar,我想要 foo 之间的所有内容。所以我为此使用了这个表达式,结果是:barbarbar。它工作得很好。

(?<=foo).*(?=foo)

现在我也想要相反的东西。所以给定字符串 foobarbarbarfoobar 我想要所有没有被 foo 包围的东西。我尝试了以下正则表达式:

(?<!foo).*(?!foo)

我期望 bar 作为结果,但它 returns 与 foobarbarbarfoobar 匹配。这对我来说没有意义。我错过了什么?

解释来自:https://regex101.com/ 我觉得不错?

(?<!foo).*(?!foo)
(?<!foo) Negative Lookbehind - Assert that it is impossible to match the regex below
foo matches the characters foo literally (case sensitive)
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible,    giving back as needed [greedy]
(?!foo) Negative Lookahead - Assert that it is impossible to match the regex below
foo matches the characters foo literally (case sensitive)

非常感谢任何帮助

我希望有人能找到更好的方法,但这种令人厌恶的做法可能会如你所愿: (.*)foo(?<=foo).*(?=foo)foo(.*)

第一个 foo 之前的文本在捕获组 1 中(对于您提供的示例,这将是空的)并且之后的文本在捕获组 2 中(在这种情况下为 'bar')

如果您希望在两端包含 'foo',请改用:(.*)(?<=foo).*(?=foo)(.*)。这将导致组 1 中的 'foo' 和组 2 中的 'foobar'。

我找到了解决方案:

^((?!foo).)+

来自 regex101 的解释

^ assert position at start of the string
1st Capturing group ((?!foo).)+
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed
Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data
(?!foo) Negative Lookahead - Assert that it is impossible to match the regex below
foo matches the characters foo literally (case sensitive)
. matches any character (except newline)