如何编写以root cause开头、以category或换行符结束的regex?
匹配需求的正则表达式
可直接使用如下正则满足你的匹配规则:
root cause.*?(?=category|\n)
正则逻辑说明
- 开头的
root cause固定匹配起始关键词 .*?为惰性匹配规则,会尽可能短的匹配后续字符,避免出现过度匹配的问题(?=category|\n)是正向零宽断言,不会将匹配到的category或者换行符纳入最终匹配结果,同时会在这两个标识第一次出现时就立刻终止匹配
效果验证
- 无换行测试文本验证
原文本:Hi there how are you. This is a test for the root cause of ice cream addiction and not the category of happiness.
匹配结果:root cause of ice cream addiction and not the,完全符合预期 - 带换行测试文本验证
原文本:
匹配结果:Hi there how are you. This is a test for the root cause of ice cream addiction and not the category of happiness.root cause of ice cream addiction,完全符合预期
补充说明
如果你使用的正则引擎默认设置为.不匹配换行符,也可以将正则简化为root cause.*?(?=category),默认规则下.本身不会越过换行符匹配,也能达到相同的效果。
内容的提问来源于stack exchange,提问作者jsy
相关产品推荐
相关产品推荐

