如何在JavaScript中反转正则表达式? [英] How can I invert a regular expression in JavaScript?

查看:384
本文介绍了如何在JavaScript中反转正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串A并想测试另一个字符串B是否不是它的一部分。这是一个非常
的简单正则表达式,其结果可以在之后反转。

I have a string A and want to test if another string B is not part of it. This is a very simple regex whose result can be inverted afterwards.

我能做到:

/foobar/.test('foobar@bar.de')

然后将其反转,如下所示:

and invert it afterwards, like this:

!(/foobar/).test('foobar@bar.de') 

我遇到的问题是,我需要在正则表达式中执行此操作而不是他们的结果。类似于:

The problem I have is, that I need to do it within the regular expression and not with their result. Something like:

/!foobar/.test('foobar@bar.de')

(这不起作用)

换句话说:正则表达式应该测试不存在并在这种情况下返回true。

In other words: the regular expression should test for a non-existence and return true in that case.

这可以用JavaScript吗?

Is this possible with JavaScript?

推荐答案

尝试:

/^(?!.*foobar)/.test('foobar@bar.de')

A(简短)说明:

^          # start of the string 
(?!        # start negative look-ahead
  .*       # zero or more characters of any kind (except line terminators)
  foobar   # foobar
)          # end negative look-ahead

因此,用简单的英语,如果字符串'foobar'可以被看到,那么正则表达式将从字符串的开头看。如果可以看到,则没有 *匹配。

So, in plain English, that regex will look from the start of the string if the string 'foobar' can be "seen". If it can be "seen" there is no* match.

*不匹配,因为它是否定看起来 - 提前!

* no match because it's negative look-ahead!

关于这个前瞻性内容的更多信息: http://www.regular-expressions.info/lookaround.html 但请注意,JavaScript仅支持预测,不支持 - 支持

More about this look-ahead stuff: http://www.regular-expressions.info/lookaround.html But Note that JavaScript only supports look-aheads, no look-behinds!

这篇关于如何在JavaScript中反转正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆