簡體   English   中英

Java 1.7。 如何在正則表達式中並排替換兩個字符?

[英]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表示的模式,並將該匹配 replacementreplacement內容。 如果你不想替換它,但是讓我們說只打印它,而不是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM