[英]Java 1.7. How to replace two characters side by side in a regular expression?
我有代碼:
String str = "1 */ * / 2";
str = str.replaceAll("\\*/", " ");
System.out.println(str);
他給了我下一個結果,這是正確的:
1 * / 2
但是我需要得到相反的結果,我這樣做:
String str = "1 */ * / 2";
str = str.replaceAll("[^\\*/]", " ");
System.out.println(str);
得到:
* / * /
但不是:
* /
我只需要將這兩個字符放在一起,單獨排除*和/
我怎樣才能做到這一點?
replaceAll(regex, replacement)
嘗試搜索由regex
表示的模式,並將該匹配 replacement
為replacement
內容。 如果你不想替換它,但是讓我們說只打印它,而不是String#replaceAll
使用Matcher#find
like
String str = "1 */ * / 2";
Pattern p = Pattern.compile("\\*/");
Matcher m = p.matcher(str);
while(m.find()){
String match = m.group();
//do something with match
System.out.println(match);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.