通过新的RegExp(myString)创建的正则表达式不起作用(反斜杠) [英] Regex created via new RegExp(myString) not working (backslashes)
问题描述
所以,我正在尝试编写一个匹配所有数字的正则表达式。这是正则表达式:
So, I'm trying to write a regex that matches all numbers. Here is that regex:
/\b[\d \.]+\b/g
我尝试在字符串上使用它:
And I try to use it on the string:
100 two 100
一切正常;它匹配两个数字。
And everything works fine; it matches both of the numbers.
但我想重写表格中的正则表达式:
But I want to rewrite the regex in the form:
new RegExp(pattern,modifiers)
因为我觉得它看起来更清晰。
所以我这样写:
Because I think it looks clearer. So I write it like this:
new RegExp('\b[\d \.]+\b','g')
但是现在它与以前的测试字符串不匹配。我已经尝试了一切,但我无法让它发挥作用。我做错了什么?
But now it won't match the former test string. I have tried everything, but I just can't get it to work. What am I doing wrong?
推荐答案
请忽略我的投票结果。你的问题是字符串中的反斜杠具有特殊含义;如果你想在正则表达式中使用反斜杠,首先需要在传递给正则表达式的字符串中获得字面反斜杠:
Please ignore my close vote. Your problem is that the backslash in a string has a special meaning; if you want a backslash in your regexp, you first need to get literal backslashes in the string passed to the regex:
new RegExp('\\b[\\d \\.]+\\b','g');
请注意,这是一个非常糟糕的(允许的)正则表达式,因为它将匹配...
作为'数字',或1 1 ... 3 42
。更好的可能是:
Note that this is a pretty bad (permissive) regex, as it will match ". . . "
as a 'number', or "1 1...3 42"
. Better might be:
/-?\d+(?:\.\d+)?\b/
请注意,这与奇怪的事情相匹配,例如 0000.3
不匹配:
Note that this matches odd things like 0000.3
also does not match:
- 领先
+
- 科学记数法,例如
1.3e7
- 缺少前导数字,例如
.4
- Leading
+
- Scientific notation, e.g.
1.3e7
- Missing leading digit, e.g.
.4
另请注意,使用RegExp构造函数(略微)较慢当然比使用RegExp文字更不惯用。当您需要从提供的字符串构造您的RegExp时,使用它只是一个好主意。大多数熟悉JavaScript的人都会发现 /.../
符号完全清楚。
Also note that using the RegExp constructor is (marginally) slower and certainly less idiomatic than using a RegExp literal. Using it is only a good idea when you need to constructor your RegExp from supplied strings. Most anyone with more than passing familiarity with JavaScript will find the /.../
notation fully clear.
这篇关于通过新的RegExp(myString)创建的正则表达式不起作用(反斜杠)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!