Regexp为什么不匹配? [英] Why doesn't Regexp match?

查看:149
本文介绍了Regexp为什么不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么这个Regexp不匹配吗?

Can anybody please tell me why doesn't this Regexp match?

var matches = ' @test'.match(new RegExp('(\s+|^)(@|!)(.*?)(\s+|$)', 'g'));

与此匹配:

var matches = '@test'.match(new RegExp('(\s+|^)(@|!)(.*?)(\s+|$)', 'g'));

我已经指定了\s+.那为什么不匹配呢?

I have already specified \s+. Why wouldn't it match it then?

推荐答案

\s不被认为是空格的缩写,因为您是从字符串而不是正则表达式文字构造正则表达式的,而在字符串内部则需要将反斜杠加倍.

\s is not recognized as the whitespace shorthand because you're constructing the regex from a string instead of a regex literal, and inside a string you need to double the backslashes.

所以您需要使用

var matches = ' @test'.match(new RegExp('(\\s+|^)([@!])(.*?)(\\s+|$)', 'g'));

var matches = ' @test'.match(/(\s+|^)([@!])(.*?)(\s+|$)/g);

这篇关于Regexp为什么不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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