简体   繁体   English

正则表达式替换字符集

[英]Regex replace a set of characters

I want to replace + - ( ) and space with an empty character in a Javascript string. 我想用Javascript字符串中的空字符替换+ - ( )space The expression I'm using is: 我正在使用的表达式是:

"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/, "");

which results in: 结果是:

"1 - (042) - 123456"

Only the + is replaced and not the other characters. +代替,其他字符不代替。 What is the error in my expression? 我的表达方式有什么错误?

When you use square brackets to list characters to remove/change or whatever, you don't want to escape them. 当您使用方括号列出要删除/更改的字符或其他内容时,您不想对其进行转义。 And I would recommend using \\s instead of 我建议使用\\s代替 , and, of course, you need the global flag - g . ,当然,您需要全局标志g

"+1 - (042) - 123456".replace(/[+()\s-]/g, "")

Use the g flag: 使用g标志:

/[\+\-\' '\(\)]/g

JS: JS:

"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/g, "");

The g indicates a "Global search", meaning that every match of the regex must be replaced. g表示“全局搜索”,表示必须替换正则表达式的每个匹配项。

You need to include g global flag inorder to make pattern to match two or more times on the same line. 您需要包括g全局标志,以使模式在同一行上匹配两次或更多次。 And alo you don't need to include single quotes inside the character class. 而且,您不必在字符类中包含单引号。

"+1 - (042) - 123456".replace(/[-+() ]/g, "");

As idmean mentioned in their answer , you should add the g(global) flag , otherwise the function will stop once the first match is found . 正如他们在答案中提到的idmean一样,您应该添加g(global)标志,否则一旦找到第一个匹配项,该函数就会停止。

However , there are some redundant escapes and characters in your RegEx. 但是,RegEx中有一些多余的转义符和字符。

That's how your RegEx can be in its simplest form : 这就是RegEx的最简单形式:

/[+) (-]/g

I didn't get why there are single quotes in your RegEx. 我不明白为什么您的RegEx中有单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM