【问题标题】:Java - Replace regex occurrences in a string [duplicate]Java - 替换字符串中出现的正则表达式[重复]
【发布时间】:2018-04-24 20:46:47
【问题描述】:

我必须用“”替换字符串中所有出现的“)(”,然后删除所有出现的“(”和“)”。 例如:(1,1)(2,2) => (1,1 2,2) => 1,1 2,2。 我已经尝试过第一步,但字符串没有改变:

String test = "(1,1)(2,2)";
test.replaceAll(Pattern.quote(")("), Pattern.quote(" "));

【问题讨论】:

  • "[\()]" 不工作?

标签: java string str-replace


【解决方案1】:

Strings 是不可变的。简单地调用replaceAll 不会修改字符串,而是返回一个新字符串。你需要做的

String test = "(1,1)(2,2)";
test = test.replaceAll(Pattern.quote(")("), " ");

或使用replace 为简单起见不使用正则表达式的方法

String test = "(1,1)(2,2)";
test = test.replace(")(", " ");

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2010-10-04
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多