javascript - 正则表达式 : substring not followed by character

标签 javascript regex node.js

假设一个正则表达式应该对包含子字符串 hello 的任何字符串测试为真,后跟任何不以 ! 或多个 !< 开头的字符串.

为清楚起见,举几个例子:

var regExp = /someExpression/;

regExp.test("hello"); // → true
regExp.test("hello!"); // → false
regExp.test("hello!!"); // → false
regExp.test("hello!sdkfjhsdfjkh"); // → false
regExp.test("hellos!dkfjhsdfjkh"); // → true
regExp.test("hello-!"); // → true
regExp.test("hello w34~342`!!"); // → true

我尝试了几种方法,这是我最好的:

var regExp = /.*hello[^!].*/;

这适用于我能想到的所有情况,但只有一个:"hello"

在这种情况下,[^!] 需要一个字符。

我如何改进此正则表达式,使其在这种情况下也能测试正确?

感谢任何形式的帮助。


编辑 - 奖励积分:

hello 前面有一个 !,所以 hello 被接受,但是 !hello 是不是。

最佳答案

你需要使用一个否定的前瞻而不是一个否定的字符类(仍然匹配,消耗字符):

var regExp = /.*hello(?!!).*/;

参见 regex demo

查看更多详细信息 regular-expressions.info :

Negative lookahead is indispensable if you want to match something not followed by something else. When explaining character classes, this tutorial explained why you cannot use a negated character class to match a q not followed by a u. Negative lookahead provides the solution: q(?!u). The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point.

编辑:

由于JS正则引擎不支持look-behind,所以需要匹配(^|[^!])hello (where (^|[^!]) 匹配字符串的开头或 ! 以外的符号),然后使用 JS 字符串方法对它做任何你需要做的事情。

关于javascript - 正则表达式 : substring not followed by character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32852533/

相关文章:

javascript - Node.js 或 Ubuntu Linux 在服务器启动时运行 cron

javascript - Ember 与数据 - 路线模型无法一致工作

regex - 如何在 R 中使用子函数

java - 递归检查字符串是否有重复模式?

c# - C# 中最好的 Regex 模式是什么,可以忽略 perl 中的某些字符组,如 (*SKIP)(*F)?

javascript - 为什么 node.js 在尝试在 localhost 上运行应用程序时需要升级?

node.js - 如何将 Express REST 层放置在 Apollo GraphQL 服务器之上?

javascript - 使用 Js 在 html 表单中输入正确的密码时导航到 url

javascript - Vue js - Vue 路由器 - 登录和刷新数据

javascript - 如何按字符串中 'word' 出现的升序对字符串数组进行排序? javascript