正则表达式 - 以特定字符串开头但不以另一个子字符串结尾 [英] Regex - starts with a particular string but does not end with another substring
本文介绍了正则表达式 - 以特定字符串开头但不以另一个子字符串结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定两个字符串 s1
和 s2
,我正在尝试编写一个正则表达式来匹配以 s1
开头但不匹配的字符串以 s2
Given two strings s1
and s2
, I am trying to write a regex that will match a string that starts with s1
but does not end with s2
示例(s1=TEST,s2=BAD)
Example (s1=TEST, s2=BAD)
- TEST-101 匹配
- TEST-SOME-DESC 匹配
- TEST-101-BAD 不应匹配
- TEST-SOME-DESC-BAD 不应匹配
这是我在这个例子中尝试过的,但它不起作用:/^TEST-.*((?!BAD))$/
Here is what I tried for this example but it does not work: /^TEST-.*((?!BAD))$/
推荐答案
试试这个:
/^(?!.+BAD$)TEST-.*/
这匹配开始,继续并拒绝以错误字符串结尾的任何内容,然后匹配所需的模式.
This matches the start, goes ahead and rejects anything ending in the bad string, then matches the desired pattern.
这是通过所有四个测试的演示(点击运行测试"" 在底部验证).
Here's a demo that passes all four of your tests (click "RUN TESTS" at the bottom to verify).
这篇关于正则表达式 - 以特定字符串开头但不以另一个子字符串结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文