烦人又奇怪的正则表达式问题:'io\.'获得单词“function”的匹配;
从节点 REPL 来看,
> 'function'.search('io\.')
5
我真的需要它只匹配“io”。而不是“函数”或中间只有“io”的任何东西...
更奇怪的事情:
> 'io'.search('io\.')
-1
> 'ion'.search('io\.')
0
所以看来我没有逃避点字符..?但我和“\”在一起......对吧?我在 http://www.regextester.com/ 和 http://regexpal.com/ 它的工作原理是我认为它应该工作的方式。
我做错了什么? node.js 中的正则表达式内容与我习惯的有些不同吗?
EDIT1:在 Google Chrome 的 javascript 控制台中我也得到了
'function'.search('io\.')
5
所以它可能是 v8 的东西......对吗?
EDIT2:我从 Firefox 的 javascript 控制台得到了相同的结果,所以它不是 v8 的东西......这里发生了什么?我真的很困惑...
From the node REPL thing,
> 'function'.search('io\.')
5
I really need it to match only "io." and not "function" or anything with just "io" in the middle...
More weird things:
> 'io'.search('io\.')
-1
> 'ion'.search('io\.')
0
So it appears I'm not escaping the dot character..? But I am with the "\"... right ? I tested it on both http://www.regextester.com/ and http://regexpal.com/ and it works the way I think it's supposed to work.
What am I doing wrong ? Is the regex stuff in node.js somewhat different then what I'm used to ?
EDIT1: In Google Chrome's javascript console I get also
'function'.search('io\.')
5
So it might be a v8 thing... right ?
EDIT2: I get the same results from Firefox's javascript console, so it's not a v8 thing... What's happening here ? I'm really confused...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的正则表达式是正确的,但是您也必须对其进行编码才能将其放入字符串中。
因此,您的(正确的)正则表达式如下所示:
但是,反斜杠也是字符串转义字符。为了创建包含该正则表达式的字符串,您必须转义反斜杠:
按照您的编写方式,该字符串实际上包含
io.
,它正确匹配function
。Your regex is right, but you have to encode it for putting it in a string, too.
So, your (correct) regex looks like this:
However, The backslash is also a string escape character. In order to create a string containing that regex, you have to escape the backslash:
The way you wrote it, the string actually contains
io.
, which correctly matchesfunction
.这里的问题是反斜杠在两个级别上用作转义字符:在字符串文字中和在正则表达式中。例如,
'\\'
是包含单个反斜杠的字符串(如果将其键入 REPL 中,您可以看到它)。有两个选项:
转义反斜杠:
'\\.'
是包含反斜杠和点的字符串,它是匹配点的正则表达式。使用正则表达式文字:
/io\./
<前><代码>> '函数'.search(/\./)
-1
The problem here is that the backslash is used as an escape character at two levels: in string literals and in regexes. For example
'\\'
is the string containing a single backslash (which you can see if you type it into the REPL).There are two options:
escape the backslash:
'\\.'
is the string containing a backslash and a dot, which is a regex that matches a dot.use a regex literal:
/io\./