问题描述
我找不到合适的正则表达式来匹配任何以某种条件结尾的not字符串.例如,我不想匹配任何以 a
结尾的内容.
I have not been able to find a proper regex to match any string not ending with some condition. For example, I don't want to match anything ending with an a
.
匹配
b
ab
1
这不匹配
a
ba
我知道正则表达式应该以 $
结尾来标记结束,但我不知道它前面应该有什么.
I know the regex should be ending with $
to mark the end, though I don't know what should preceed it.
编辑:原始问题似乎不是我的案例的合法示例.那么:如何处理多个字符?说什么不以 ab
结尾?
Edit: The original question doesn't seem to be a legit example for my case. So: how to handle more than one character? Say anything not ending with ab
?
我已经能够解决这个问题,使用这个线程:
I've been able to fix this, using this thread:
.*(?:(?!ab).).$
尽管这样做的缺点是,它不匹配一个字符的字符串.
Though the downside with this is, it doesn't match a string of one character.
推荐答案
你不给我们语言,但如果你的正则表达式风格支持 看看断言背后,这就是你所需要的:
You don't give us the language, but if your regex flavour support look behind assertion, this is what you need:
.*(?<!a)$
(?<!a)
是一个否定的后视断言,它确保在字符串(或带有 m
修饰符的行)结束之前,没有字符a".
(?<!a)
is a negated lookbehind assertion that ensures, that before the end of the string (or row with m
modifier), there is not the character "a".
您也可以轻松地使用其他字符扩展它,因为这会检查字符串而不是字符类.
You can also easily extend this with other characters, since this checking for the string and isn't a character class.
.*(?<!ab)$
这将匹配不以ab"结尾的任何内容,在 Regexr 上查看
This would match anything that does not end with "ab", see it on Regexr
这篇关于字符串的正则表达式不以给定后缀结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!