简体   繁体   English

使用replaceAll()替换字符串中所有出现的字符

[英]Use replaceAll() to replace all occurrences of characters in string

Let's say I have this example string: 假设我有以下示例字符串:

String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";

And I want to get this string as a result of a replacement procedure: 我想通过替换过程得到这个字符串:

String textreplaced =  "**/src/pt/data,**/src/pt/groove";

Basically, what I wanted was to replace all occurrences of characters before the /src with **/. 基本上,我想要用** /替换/ src之前出现的所有字符。 This might be tricky and I've tried to capture groups between the comma and the /src text but it doesn't work as I was expecting. 这可能很棘手,并且我尝试捕获逗号和/ src文本之间的组,但是它没有按我预期的那样工作。

I was using the replaceAll() method (wihtin Jenkins). 我正在使用replaceAll()方法(wihtin Jenkins)。

Does anyone have any idea how can I get it? 有谁知道我怎么得到它?

Use positive lookahead : 使用正向前瞻

String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";

System.out.println(text.replaceAll("([\\w/]+)(?=/src)", "**")); // **/src/pt/data,**/src/pt/groove

Here's an alternative non-regex based answer, in case anyone wants it: 如果有人需要,这是一个基于非正则表达式的替代答案:

String textreplaced = "";
String[] split = text.split(",");
for (int i = 0; i < split.length; i++) {
    textreplaced += "**" + split[i].substring(split[i].indexOf("/src"));
    if (i != split.length - 1) {
        textreplaced += ",";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM