[英]How do you replace all strings that are not between two characters?
Example (replacing 'text' with '...'):示例(将 'text' 替换为 '...'):
Before: text(text)text之前:文本(文本)文本
After: ...(text)...之后:...(文本)...
In this case it is easier to find what you want to keep, and replace the rest.在这种情况下,更容易找到您想要保留的内容,并更换 rest。
Eg like this:比如像这样:
static String abbreviate(String input, String openTag, String closeTag) {
String regex = Pattern.quote(openTag) + ".*?" + Pattern.quote(closeTag);
StringBuilder buf = new StringBuilder();
int start = 0;
for (Matcher m = Pattern.compile(regex).matcher(input); m.find(); start = m.end()) {
if (start < m.start())
buf.append("...");
buf.append(m.group());
}
if (start < input.length())
buf.append("...");
return buf.toString();
}
Test测试
System.out.println(abbreviate("text(text)text(text)text", "(", ")"));
System.out.println(abbreviate("text$text$text$text$text$text", "$", "$"));
System.out.println(abbreviate("text(text)text", ")", "("));
Output Output
...(text)...(text)...
...$text$...$text$...
...
You need to iterate over the characters and only append those that are between the two specified characters.您需要遍历字符并且仅 append 那些在两个指定字符之间的字符。 This can be done as follows:
这可以按如下方式完成:
private String splitStr(String str, char first, char second) {
StringBuilder sb = new StringBuilder();
if(str.isEmpty() || str.indexOf(first) < 0 || str.indexOf(second) < 0)
return sb.toString();
char[] chars = str.toCharArray();
boolean append = false;
for(char c : chars) {
if(c == first) {
sb.append(c);
append = true;
}else if(c == second) {
sb.append(c);
append = false;
}else if(append)
sb.append(c);
}
return sb.toString();
}
Some sample cases are:一些示例案例是:
"text(text)text(text)text(text)text" => "(text)(text)(text)"
"text(text)text" => "(text)"
String s = "text(text)text";
String newString = s.replace("text", "...");
System.out.println(newString); //returns ...(...)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.