替换除正/负数以外的所有内容 [英] Replace everything except positive/negative numbers
问题描述
已经回答了许多问题来替换所有正数.但是,我找不到任何保留正数和负数的答案.我想替换所有不是数字(正数或负数)的东西.输出应如下,例如.
There are many questions already answered for replacing everything positive numbers. But, I couldn't find any answer which preserves both positive and negative numbers. I want to replace everything that isn't number(positive or negative). The output should be the following eg.
<代码>0 |成功.id - 1234| -> 0 1234
和
<代码>-10 |失败.id - 2345| -> -10 2345
显然这回答了积极的部分.
Apparently this answers for the positive part.
推荐答案
您可以使用此正则表达式来匹配正/负整数:
You can use this regex to match positive/negative integers:
[+-]?\b\d+\b
匹配包括小数在内的正/负数:
to match positive/negative numbers including decimals:
[+-]?\b\d+(?:\.\d+)?\b
请注意,与其使用替换,不如在 Pattern
和 Matcher
API 中使用上述正则表达式,然后获取匹配的数据.
Please note that rather than using replace you would be better off using above regex in Pattern
and Matcher
APIs and just get your matched data.
如果您只能使用替换,请使用:
In case you can only use replace then use:
str = str.replaceAll( "([+-]?\\b\\d+\\b)|\\S+[ \\t]*", "$1" );
这篇关于替换除正/负数以外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!