我有代码:
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)尝试搜索正则表达式表示的模式,并用替换内容替换匹配的内容.如果您不想替换它,而只说打印它,而不是String#replaceAll则使用Matcher#find
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);
}