英文:
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
(?<=foo).*?(?=bar|$)
I also tried
(?<=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)|(?<=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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论