Regex replace the colon prefix in a comma-separated list except for the one quoted

I would like to have Regexp which replaces the colons ( :) with question marks ( ?), as shown below.
But it must keep colons if they are inside single quotes ( ').

For example, this input line:

(: a,: abc, 'quoted with: colon, and comma',: more)

Must be changed to:

(? a,? abc, 'quoted with: colon, and comma',? more)
0
source share
3 answers

This is another solution that works with replaceAll.

Raw regular expression:

((?:^\(|\G)(?: *'(?:[^'\\]|\\.)*' *,| *[^:' ][^,]* *,)* *):([^,]* *(?:,|\)$))

Quote line (used in replaceAll):

"((?:^\\(|\\G)(?: *'(?:[^'\\\\]|\\\\.)*' *,| *[^:' ][^,]* *,)* *):([^,]* *(?:,|\\)$))"

Replacement (used in replaceAll):

"$1?$2"

Input Example:

(  :a  ,  :abc,  'quoted with :colon, and comma', skdhfks'sdfkdf  , :sdf, 'sdfds\'f', :sdfksdf, sdkhfksd , :dfsd,  sdfk'fjsdhfkf, 'werwer', :sdf, :Sdf, skhfskjdf, 'asdads\' :asdkahsd ad'   )

:

(  ?a  ,  ?abc,  'quoted with :colon, and comma', skdhfks'sdfkdf  , ?sdf, 'sdfds\'f', ?sdfksdf, sdkhfksd , ?dfsd,  sdfk'fjsdhfkf, 'werwer', ?sdf, ?Sdf, skhfskjdf, 'asdads\' :asdkahsd ad'   )

, , . ' , . ' - \. , . (:a, , :b).

DEMO

, .

. (), .

(?:^\(|\G)(?: *'(?:[^'\\]|\\.)*' *,| *[^:' ][^,]* *,)* *:[^,]* *(?:,|\)$)

( , , ):

(?:^\(|\G)
(?:
 *'(?:[^'\\]|\\.)*' *,
|
 *[^:' ][^,]* *,
)*
 *:[^,]* *
(?:,|\)$)

: , , , .

(?:^\(|\G), ( \G.

, , - '(?:[^'\\]|\\.)*', [^:' ][^,]*, ' : ,. \\., \, . *.

, *, , .

: :[^,]*.

(?:,|\)$), , ) ,. \G.

+1
String str = "(:a,:abc,'quoted with :colon, and comma',:more)";
StringBuffer sb = new StringBuffer();
boolean inQuote = false;
for (char c : str.toCharArray()) {
    if (c == '\'') {
        inQuote = !inQuote;
        sb.append(c);
    } else if (inQuote) {
        sb.append(c);
    } else if(c == ':') {
        sb.append('?');
    } else {
        sb.append(c);
    }
}
str = sb.toString();
System.out.println(str);

(?a,?abc,'quoted with :colon, and comma',?more). . , , .

+2

:, even numbers quotes ('). : -

String str = "(:a,:abc,'quoted with :colon, and comma',:more)";     
str = str.replaceAll("[:](?=(?:[^']*'[^']*')*[^']*$)", "?");

System.out.println(str);

: -

(?a,?abc,'quoted with :colon, and comma',?more)

, : quotes quotes, , , , , ?.

+1

All Articles