I need to replace all consecutive single quotes with a single double quote:
// ''Hello World'' -> "Hello World"
// '''It's me.'''' -> "It's me."
// ''''Oh'' ''No''' -> "Oh" "No"
// ''This'''Is''Fine'' -> "This"Is"Fine"
I feel like this can be solved with a regex, but I don't know where to start.
Here is my current solution:
private fix(String line) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < line.length(); ++i) {
builder.append("'");
}
while (builder.length() > 1) {
line = line.replace(builder.toString(), "\"");
builder.deleteCharAt(0);
}
return line;
}
There are different so-called quantifiers to define that a character can/must be repeated a given number of time.
Probably the most known are * (zero or more occurences) and + (one or more occurences). The quantifier that is of help for you in your case is {2,} which means "two or more occurences". This is a specialization of the more general {min occurences,max occurences} quantifier.
So you can do it like that:
line.replaceAll("'{2,}", "\"");
In the JavaDocs its defined at http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#greedy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With