Javascript 正则字符串替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13726429/
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
regex string replace
提问by Patrick
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation.
我正在尝试使用正则表达式进行基本的字符串替换,但我找到的答案似乎没有帮助 - 他们直接回答每个人的独特要求,几乎没有解释。
I am using str = str.replace(/[^a-z0-9+]/g, '');at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character.
我目前正在使用str = str.replace(/[^a-z0-9+]/g, '');。但我想做的是允许所有字母数字字符(az 和 0-9)以及“-”字符。
Could you please answer this and explain how you concatenate expressions.
你能否回答这个问题并解释你如何连接表达式。
回答by koopajah
This should work :
这应该工作:
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
之间的一切都表明您正在寻找什么
/is here to delimit your pattern so you have one to start and one to end[]indicates the pattern your are looking for on one specific character^indicates that you want every character NOT corresponding to what followsa-zmatches any character between 'a' and 'z' included0-9matches any digit between '0' and '9' included (meaning any digit)-the '-' charactergat the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string
/在这里划定你的模式,所以你有一个开始和一个结束[]表示您在一个特定字符上寻找的模式^表示您希望每个字符不对应于以下内容a-z匹配包含在 'a' 和 'z' 之间的任何字符0-9匹配包含在 '0' 和 '9' 之间的任何数字(意味着任何数字)-人物g最后是一个特殊参数,表示您不希望正则表达式在匹配您的模式的第一个字符上停止,而是在整个字符串上继续
Then your expression is delimited by /before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
然后你的表达式由/之前和之后分隔。所以在这里你说“每个不是字母、数字或'-'的字符都将从字符串中删除”。
回答by VisioN
Just change +to -:
只需更改+为-:
str = str.replace(/[^a-z0-9-]/g, "");
You can read it as:
你可以把它读成:
[^ ]: match NOT from the set[^a-z0-9-]: match if nota-z,0-9or-/ /g: do global match
[^ ]: 从集合中不匹配[^a-z0-9-]: 如果没有匹配a-z,0-9或者-/ /g: 做全局匹配
More information:
更多信息:
回答by Samuel
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:
您的字符类(方括号中的部分)表示您想要匹配除 0-9 和 az 和 + 之外的任何内容。您没有明确说明要匹配多少个 az 或 0-9,但我认为 + 表示您要替换至少一个字母数字字符的字符串。它应该改为:
str = str.replace(/[^-a-z0-9]+/g, "");
Also, if you need to match upper-case letters along with lower case, you should use:
此外,如果您需要匹配大写字母和小写字母,您应该使用:
str = str.replace(/[^-a-zA-Z0-9]+/g, "");

