[英]How to replace just numbers in string using regex in Java?
我有這樣的字符串
"{"name:John","Age:15","width:500","height:300"},{"name:Mike","Age:25","width:600","height:400"}";
我怎樣才能像寬度和高度之后那樣替換數字
"{"name:John","Age:15","width:100","height:100"},{"name:Mike","Age:25","width:100","height:100"}";
謝謝
使用此正則表達式進行搜索:
(width|height):\d+
並替換為:
$1:100
Java:
str = str.replaceAll("(width|height):\\d+", "$1:100");
在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"));
演示程序的輸出:
"{"name:John","Age:15","width:100","height:100"},{"name:Mike","Age:25","width:100","height:100"}";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.