替换除正/负数以外的所有内容 [英] Replace everything except positive/negative numbers

查看:28
本文介绍了替换除正/负数以外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经回答了许多问题来替换所有正数.但是,我找不到任何保留正数和负数的答案.我想替换所有不是数字(正数或负数)的东西.输出应如下,例如.

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

请注意,与其使用替换,不如在 PatternMatcher 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆