简体   繁体   English

如何在Java中使用正则表达式替换字符串中的数字?

[英]How to replace just numbers in string using regex in Java?

I have String like this 我有这样的字符串

"{"name:John","Age:15","width:500","height:300"},{"name:Mike","Age:25","width:600","height:400"}";

how i can replace the numbers just after width and height to be like this 我怎样才能像宽度和高度之后那样替换数字

"{"name:John","Age:15","width:100","height:100"},{"name:Mike","Age:25","width:100","height:100"}";

Thanks 谢谢

Search using this regex: 使用此正则表达式进行搜索:

(width|height):\d+

and replace with: 并替换为:

$1:100

RegEx Demo 正则演示

Java: Java:

str = str.replaceAll("(width|height):\\d+", "$1:100");

In Java, we can use a list of alternatives in a look-behind ( see Java takes things a step further by allowing finite repetition ), and their length does not have to be identical: 在Java中,我们可以在后面使用替代列表( 请参阅Java通过允许有限重复来使事情更进一步 ),并且它们的长度不必相同:

String str = "\"{\"name:John\",\"Age:15\",\"width:500\",\"height:300\"},{\"name:Mike\",\"Age:25\",\"width:600\",\"height:400\"}\";";
System.out.println(str.replaceAll("(?i)(?<=width:|height:)\\d+", "100"));

Output of a demo program : 演示程序的输出:

"{"name:John","Age:15","width:100","height:100"},{"name:Mike","Age:25","width:100","height:100"}";

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

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