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
我尝试使用正则表达式捕获组,但如何将一个捕获组替换为另一个捕获组?
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
我尝试使用正则表达式捕获组,但如何将一个捕获组替换为另一个捕获组?
利用
https://www.tutorialspoint.com/java/java_string_replaceall.htm
并做类似的事情
a.replaceAll("\\[\\[(\\w+)[^\\[]+\\]\\]", "$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();
a.replaceAll("\\[\\[(\\*\\*\\w+\\*\\*)(?:\\s\\w+\\s?)+\\]\\]", "$1");