如何使用正则表达式检查字符串是否以特定模式开头,但不以特定模式结尾。
示例:
Must StartsWith: "US.INR.USD.CONV"
Should not end with: ".VALUE"
Passes Regex: "US.INR.USD.CONV.ABC.DEF.FACTOR"
Fails Regex Check: "US.INR.USD.CONV.ABC.DEF.VALUE"
我正在使用C#。
^US\.INR\.USD\.CONV(?!.*?\.VALUE$).*$
^US\.INR\.USD\.CONV
- 匹配以 US.INR.USD.CONV
开头的输入(?!.*?\.VALUE$)
- 负向先行断言,确保该行不以 .value
结尾^US\.INR\.USD\.CONV.*(?<!\.VALUE)$
(?<!\.VALUE)$ ==>Makes sure regex engine looks behind and checks if `.VALUE` is not there when it reaches the end of string.
你不需要正则表达式。你可以使用String.StartsWith
和String.EndsWith
。
if(val.StartsWith("US.INR.USD.CONV") && !val.EndsWith(".VALUE"))
{
// valid
}
正如您在对anubhava答案的评论中提到的,您也可以通过检查结尾是否为".PERCENT"来实现此操作。
if(val.StartsWith("US.INR.USD.CONV") &&
!val.EndsWith(".VALUE") &&
!val.EndsWith(".PERCENT"))
{
// valid
}
在我看来,这使得代码更易读,并且几乎肯定会执行得更快。
(?!.*?\.(?:VALUE|PERCENT)$)
。 - vks.VALUE
,也就是任何字符之前的"VALUE",对吧? - 1252748