替换任何字符的正则表达式(数字/,除外) [英] regex that replace any chars (except number/, .)
问题描述
我有一个字符串。我需要解析它,替换任何字符(数字除外( 0
到 9
), ,
和。
。
I have a string. I need to parse it, replacing any chars (except numbers (0
to 9
),,
and .
.
如何使用javascript进行操作?
How can I do it with javascript?
尝试:
string.replace(/[a-zA-Z]*/, "");
但似乎它不起作用。此外,我需要任何字符,不仅是aZ(也是?,/,空格等等,如前所述,,和。
but seems it doesnt works. Also, I need ANY chars, not only a-Z (also ?, /, white space, and so on, expect, as said, , and .
推荐答案
使用否定角色类
[^0-9,.]
并且放入任何你不想被替换的角色,它将匹配所有其他角色。
and put in any character you don't want to be replaced, it will match all the others.
看到它在Regexr上
您可以通过添加量词来优化它 +
,以便替换这些字符的序列s立即而不是每个。
You can optimize it by adding a quantifier +
, so that it replaces a sequence of those characters at once and not each by each.
string.replace(/[^0-9,.]+/g, "");
正如Felix Kling所指出的,使用全局选项 g
匹配所有出现的模式。
As Felix Kling pointed out, its important to use the global option g
to match on all occurrences of the pattern.
看到它在Regexr上
这篇关于替换任何字符的正则表达式(数字/,除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!