JDK 7. 什麼是正則表達式處理str1並獲得所有內部數字的平方?我們可以計算沒有循環語句的字符串中的數字表達式(通過正則表達式)嗎?
String str1="ab cd 2 4 ef 12x";
...
System.out.println(str1.replaceAll("...", "..."));
我們可以得到安慰了作爲
ab cd 4 16 ef 144x
不循環使用?
也許它是如此複雜或不可能......不幸的是,我不知道。 預先感謝您。
JDK 7. 什麼是正則表達式處理str1並獲得所有內部數字的平方?我們可以計算沒有循環語句的字符串中的數字表達式(通過正則表達式)嗎?
String str1="ab cd 2 4 ef 12x";
...
System.out.println(str1.replaceAll("...", "..."));
我們可以得到安慰了作爲
ab cd 4 16 ef 144x
不循環使用?
也許它是如此複雜或不可能......不幸的是,我不知道。 預先感謝您。
這是不可能做到的,在一個replaceAll
電話,甚至兩個,因爲匹配的子串無法在運行中進行評估(您可以在Perl中執行此操作,但不能在Java中執行此操作)。
因此,正如我所提到的,一種解決方法是將Matcher#appendReplacement
與循環一起使用。
參見一個sample demo:
String s = "ab cd 2 4 ef 12x";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("\\d+").matcher(s);
while (m.find()) {
m.appendReplacement(result,
String.valueOf((int)Math.pow(Double.parseDouble(m.group(0)), 2))); // Calculate
}
m.appendTail(result);
System.out.println(result.toString());
我有一個循環的解決方案,可能是它的幫助你找到其他的解決方案
String str="ab cd 2 4 ef 12x";
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str);
while(m.find()) {
System.out.println(Math.pow(Integer.parseInt(m.group(1)), 2));
}
輸出: 4.0 16.0 144.0
正則表達式是大約模式匹配和字符串替換,不計算。 –
這是不是Perl,你有'/ e'修飾符。使用匹配數字的正則表達式的「Matcher#appendReplacement」,並在'while(m.find())'塊內執行計算。 –
您可以使用Streams API來解碼所有單詞/數字,將數字平方並加入生成的字符串。 –