Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace consecutive characters in a string

Tags:

java

regex

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;
}
like image 332
budi Avatar asked Dec 13 '25 02:12

budi


1 Answers

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

like image 174
Matthias Wimmer Avatar answered Dec 14 '25 14:12

Matthias Wimmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!