简体   繁体   English

如何在正则表达式中仅返回数字和空格?

[英]How can I return only numbers and white space in Regular Expression?

I would like to have a regular expression which returns only the numbers and the white space which I've inserted. 我想有一个仅返回数字和插入的空格的正则表达式。 ie

012 345 678 

or 要么

012 345 678 910.

Any suggestion please? 有什么建议吗?

You could remove any other character except digits and white space. 您可以删除数字和空格以外的任何其他字符。 Here's an example in PHP: 这是PHP中的示例:

$output = preg_replace('/[^\d\s]/', '', $str);

Then the remaining string does only consist of digits and white space characters. 然后,剩余的字符串仅由数字和空格字符组成。

A Java example which uses the regular expression (\\d+(\\s\\d)?)* : 一个使用正则表达式(\\d+(\\s\\d)?)*的Java示例:

Pattern regex = Pattern.compile("(\\d+(\\s\\d)?)*", Pattern.CANON_EQ);
Matcher regexMatcher = regex.matcher("i.e 012 345 678 or 012 345 678 910.");
if (regexMatcher.find()) {
    resultString = regexMatcher.group();
} 

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

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