Javascript 在正则表达式中查找加号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2021053/
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
Finding Plus Sign in Regular Expression
提问by Justin Helgerson
var string = 'abcd+1';
var pattern = 'd+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
I found out last night that if you try and find a plus sign in a string of text with a Javascript regular expression, it fails. It will not find that pattern, even though it exists in that string. This has to be because of a special character. What's the best way to find a plus sign in a piece of text? Also, what other characters will this fail on?
我昨晚发现,如果您尝试在带有 Javascript 正则表达式的文本字符串中查找加号,则会失败。它不会找到那个模式,即使它存在于那个字符串中。这一定是因为一个特殊的字符。在一段文本中找到加号的最佳方法是什么?另外,还有哪些其他角色会失败?
回答by Quentin
Plus is a special characterin regular expressions, so to express the character as data you must escape it by prefixing it with \.
Plus 是正则表达式中的一个特殊字符,因此要将字符表示为数据,您必须通过在它前面加上\.
var reg = /d\+1/;
回答by kennebec
\-\.\/\[\]\ **always** need escaping
\*\+\?\)\{\}\| need escaping when **not** in a character class- [a-z*+{}()?]
But if you are unsure, it does no harm to include the escape before a non-word character you are trying to match.
但是,如果您不确定,在您尝试匹配的非单词字符之前包含转义符也无妨。
A digit or letter is a word character, escaping a digit refers to a previous match, escaping a letter can match an unprintable character, like a newline (\n), tab (\t) or word boundary (\b), or a a set of characters, like any word-character (\w), any non-word character (\W).
数字或字母是单词字符,转义数字是指之前的匹配,转义字母可以匹配不可打印的字符,例如换行符 (\n)、制表符 (\t) 或单词边界 (\b) 或 aa字符集,如任何单词字符 (\w)、任何非单词字符 (\W)。
Don't escape a letter or digit unless you mean it.
除非您是认真的,否则不要转义字母或数字。
回答by YOU
Just a note,
只是一个笔记,
\should be \\in RegExp pattern string, RegExp("d\+1")will not work and Regexp(/d\+1/)will get error.
\应该\\在 RegExp 模式字符串中,RegExp("d\+1")将不起作用并且Regexp(/d\+1/)会出错。
var string = 'abcd+1';
var pattern = 'd\+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
//3
回答by Ash
You should use the escape character \ in front of the + in your pattern. eg. \+
您应该在模式中的 + 前面使用转义字符 \。例如。\+
回答by Kaleb Brasee
You probably need to escape the plus sign:
您可能需要转义加号:
var pattern = /d\+1/
The plus sign is used in regular expressions to indicate 1 or more characters in a row.
加号在正则表达式中用于表示一行中的 1 个或多个字符。
回答by Khoa Phung
It should be var pattern = '/d\\+1/'.
应该是var pattern = '/d\\+1/'。
The string will escape '\\'as '\'('\\+'--> '\+') so the regex object init with /d\+1/
该字符串将转义'\\'为'\'('\\+'--> '\+'),因此正则表达式对象 init 与/d\+1/
回答by canmustu
Easy way to make it :
简单的制作方法:
The alphabet is : "[\+]"
字母是:“ [\+]”
All plus signs we want to find : "[\+]*"
我们要查找的所有加号:“ [\+]*”

