加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java 1.7.如何在正则表达式中并排替换两个字符?

发布时间:2020-12-14 19:30:06 所属栏目:Java 来源:网络整理
导读:我有代码: String str = "1 */ * / 2";str = str.replaceAll("*/"," ");System.out.println(str); 他给了我下一个结果,这是正确的: 1 * / 2 但是我需要得到相反的结果,我这样做: String str = "1 */ * / 2";str = str.replaceAll("[^*/]"," ");System

我有代码:

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读