Home > OS >  Replace in pairs using regex
Replace in pairs using regex

Time:10-06

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();
    }

CodePudding user response:

To convert straight double quotation marks into curly double quotation marks you can use a regex that will match a pair of straight quotation marks while capturing any chars other than straight double quotation marks in between and replace with the backreference to the captured value inside curly double quotation marks:

.replaceAll("\"([^\"]*)\"", "„$1”")

See the regex demo. Details

  • " - a " char
  • ([^"]*) - Capturing group 1 ($1 in the replacement pattern refers to this group value): any zero or more (*) chars other than " ([^"] is a negated character class)
  • " - a " char.

See the Java demo:

String s = "Some \"text\"";
System.out.println(s.replaceAll("\"([^\"]*)\"", "„$1”")); 
// => Some „text”
  • Related