0

Java中对字符串进行以下替换的最佳方法是什么:

我有类似于此的文本:

one two [[**my_word** other words]] three four [[**my_other_word** other words]] five six

我想要以下文字

one two **my_word** three four **my_other_word** five six

我尝试使用正则表达式捕获组,但如何将一个捕获组替换为另一个捕获组?

4

3 回答 3

3

利用

https://www.tutorialspoint.com/java/java_string_replaceall.htm

并做类似的事情

a.replaceAll("\\[\\[(\\w+)[^\\[]+\\]\\]", "$1");
于 2017-01-31T15:37:33.897 回答
1

根据您的需求,您可以使用像

a.replaceAll("\\[\\[(\\*\\*\\w+\\*\\*).*?\\]\\]", "$1");

或者更复杂的版本,您可以控制用什么替换每个匹配项。

String inputString = "one two [[**my_word** other words]] three four [[**my_other_word** other words]] five six";
Pattern pattern = Pattern.compile("\\[\\[(\\*\\*\\w+\\*\\*).*?\\]\\]", Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputString);
StringBuffer outputBuffer = new StringBuffer();
while (matcher.find()) {
    String match = matcher.group(1);        
    matcher.appendReplacement(outputBuffer, match);
}
matcher.appendTail(outputBuffer);

String output = outputBuffer.toString();
于 2017-01-31T15:47:18.387 回答
1
a.replaceAll("\\[\\[(\\*\\*\\w+\\*\\*)(?:\\s\\w+\\s?)+\\]\\]", "$1");
于 2017-01-31T15:39:20.773 回答