JavaScript Regex,在哪里使用转义字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5514349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Regex, where to use escape characters?
提问by Avien
The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'
正则表达式允许以下字符:字母数字、空格、“-”、“_”、“&”、“()”和“/”
this is the expression
这是表达式
[\s\/\)\(\w&-]
I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try.. any suggestions?
我已经在各种在线测试人员中测试过它并且知道它有效,但我无法让它在代码中正常工作。我尝试任何操作时都会遇到 sysntax 错误.. 有什么建议吗?
var programProductRegex = new RegExp([\s\/\)\(\w&-]);
回答by R. Martinho Fernandes
You can use the regular expression syntax:
您可以使用正则表达式语法:
var programProductRegex = /[\s\/\)\(\w&-]/;
You use forward slashes to delimit the regex pattern.
您使用正斜杠来分隔正则表达式模式。
If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they're also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:
如果使用 RegExp 对象构造函数,则需要传入一个字符串。因为反斜杠是 JavaScript 字符串中的特殊转义字符,它们也是正则表达式中的转义字符,所以您需要使用两个反斜杠在字符串中进行正则表达式转义。使用字符串的等效代码将是:
var programProductRegex = new RegExp("[\s\/\)\(\w&-]");
All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.
原始正则表达式中的所有反斜杠都需要在字符串中转义才能正确解释为反斜杠。
Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.
当然第一种选择更好。当您从某处获取字符串并希望从中生成正则表达式时,构造函数很有用。
var programProductRegex = new RegExp(userInput);
回答by 3rgo
If you are using a String and want to escape characters like (
, you need to write \\(
(meaning writing backslash, then the opening parenthesis => escaping it).
如果您使用的是 String 并且想要转义像 那样的字符,则(
需要编写\\(
(意思是写反斜杠,然后是左括号 => 转义它)。
If you are using the RegExp
object, you only need one backslash for each character (like \(
)
如果您正在使用该RegExp
对象,则每个字符只需要一个反斜杠(例如\(
)
回答by Toto
Enclose your regex with delimiters:
用分隔符将正则表达式括起来:
var programProductRegex = /[\s\/)(\w&-]/;