java Java从字符串中删除除x以外的非数字字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10708236/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:12:47  来源:igfitidea点击:

Java remove non numeric characters from string except x

javaregex

提问by Code Junkie

I'm trying to remove all non numeric characters from string except for x. I'm a little confused.

我正在尝试从字符串中删除除 x 之外的所有非数字字符。我有点困惑。

my current code

我目前的代码

number.replaceAll("[^\d\x]", "")

Thanks in advance.

提前致谢。

回答by Nurlan

use this: [^x0-9]

用这个: [^x0-9]

You may check it on http://gskinner.com/RegExr/

您可以在http://gskinner.com/RegExr/查看

回答by stema

Your regex is

你的正则表达式是

number.replaceAll("[^\dxX]+", "");

No need to escape normal characters inside a character class. An improvement is also to have the quantifier +after the character class, that way sequences of those characters are replaced at once and not each char on its own.

无需转义字符类中的普通字符。一个改进也是+在字符类之后使用量词,这样这些字符的序列会被一次替换,而不是每个字符都单独替换。

Read some regex basics on Xisb: What absolutely every Programmer should know about regular expressions

阅读有关Xisb 的一些正则表达式基础知识:绝对每个程序员都应该了解的有关正则表达式的知识

回答by Code Junkie

I figured it out, maybe there's a better way to do it though.

我想通了,也许有更好的方法来做到这一点。

number.replaceAll("[^\d+xX]", "");

回答by Hakan Serce

You should use this:

你应该使用这个:

number.replaceAll("[\D&&[^x]]", "")