使用正则表达式进行字符串求反

发布于 2024-07-27 12:51:05 字数 211 浏览 5 评论 0原文

是否可以在正则表达式中进行字符串否定? 我需要匹配所有不包含字符串 ".." 的字符串。 我知道您可以使用 ^[^\.]*$ 来匹配所有不包含 "." 的字符串,但我需要匹配多个字符。 我知道我可以简单地匹配包含 ".." 的字符串,然后否定匹配的返回值以获得相同的结果,但我只是想知道这是否可能。

Is it possible to do string negation in regular expressions? I need to match all strings that do not contain the string "..". I know you can use ^[^\.]*$ to match all strings that do not contain "." but I need to match more than one character. I know I could simply match a string containing ".." and then negate the return value of the match to achieve the same result but I just wondered if it was possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

悲欢浪云 2024-08-03 12:51:05

您可以使用负向先行:

^(?!.*\.\.).*$

如果表达式可以在字符串中的任何位置找到两个句点的序列,则这会导致表达式不匹配。

You can use negative lookaheads:

^(?!.*\.\.).*$

That causes the expression to not match if it can find a sequence of two periods anywhere in the string.

栩栩如生 2024-08-03 12:51:05
^(?:(?!\.\.).)*$

仅当字符串中任何地方没有两个连续的点时才匹配。

^(?:(?!\.\.).)*$

will only match if there are no two consecutive dots anywhere in the string.

看透却不说透 2024-08-03 12:51:05

如果您的正则表达式引擎不支持负向先行,请将您想要的内容表达为非点或点后跟非点的任意多次重复。 (另一种思考方式是,如果您没有看到点,那么您很高兴,但是如果您确实看到了点,则下一个字符必须是非点。)请记住接受由点组成的字符串没有别的。

作为正则表达式,上面是

^([^.]|\.[^.])*\.?$

注意这个模式匹配空字符串,因为它不包含点-点。

If your regex engine does not support negative lookahead, then express what you want as arbitrarily many repetitions of either non-dot or dot followed by non-dot. (Another way to think of this is if you don’t see a dot, then you’re happy, but if you do see a dot, the next character must be not-dot.) Remember to accept the string consisting of a dot and nothing else.

As a regex, the above is

^([^.]|\.[^.])*\.?$

Note that this pattern matches the empty string because it does not contain dot-dot.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文