正则表达式以获取两个字符串之间的字符串,或直到主字符串的结尾。

huangapple go评论49阅读模式
英文:

Regex expression to get the string between two strings,or until either end of the main string

问题

(?<=foo|^).*?(?=bar|$) 应该可以满足你的需求,它可以匹配在String1("foo")和String2("bar")之间的内容,如果其中一个字符串不存在,也会匹配到主字符串的末尾。

英文:

I am trying to write a regex that gets the content between two strings, String1 and String2 but in case either of the two strings are not present I want to match until the end of the main string.
For example: hi_foo123xyz2-3bar_hello, foo123xyz2-3bar , foo123xyz2-3 123xyz2-3bar and 123xyz2-3 the intended match is 123xyz2-3.

I tried different approaches using Lookaheads and Lookbehinds and I feel that I only need a single step but It seems far from reach.
The closest I could get is something like this

(?&lt;=foo).*?(?=bar|$)

I also tried

(?&lt;=foo|^).*?(?=bar|$)

but it seems to break everything.

答案1

得分: 0

匹配的技巧是仅当没有 foo 出现时才匹配 ^,使用这个表达式 ^(?!.*foo),然后创建一个 foo 的肯定后发断言的选择。

类似地,使用一个 bar 的前瞻断言 或者 输入的结尾 $

(^(?!.*foo)|(?<=foo)).*?((?=bar)|$)

查看演示链接

请注意,选择是从左到右匹配的,也就是说,只有在左边的不匹配时才尝试右边的匹配。

英文:

The trick is to match ^ only when there is no foo using this expression ^(?!.*foo), then create an alternation of that or a lookbehind for foo.

Similarly, use a lookahead for bar or end of input $.

(^(?!.*foo)|(?&lt;=foo)).*?((?=bar)|$)

See live demo.

Recall that alternations are match left to right - ie the right is only attempted if the left doesn't match.

huangapple
  • 本文由 发表于 2023年3月8日 18:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定