I'd like to replace a pair of quotation marks in a string. In other words, there has to be an event count of question marks.
The first replacement is „, the second ”.
Simple input: Some "text"
Output: Some „text”
I wrote a simple code to deal with that (down below) but I wonder whether there is a simpler way, e.g. using regex. My simple regex .*(").+(?=(")) finds a pair of quatation marks but it doesn't check whether the overall count of question marks is even. Is there a way to achieve what I want using regex?
My Java code:
private static String replace(String s) {
if (s.isEmpty()) {
return s;
}
long count = s.chars()
.filter(c -> c == '"')
.count();
if (count % 2 != 0) {
return s;
}
final StringBuilder sb = new StringBuilder(s.length());
boolean replaceFirst = true;
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c != '"') {
sb.append(c);
} else {
sb.append(
replaceFirst ? "„" : "”"
);
if (replaceFirst) {
replaceFirst = false;
}
}
}
return sb.toString();
}