user3607869
user3607869

Reputation: 315

Replace the commas which are not inside parenthesis,quotes

For the given input string abc,[def,ghi,ijk],lm,(no,pq,rs),[tu,vw,xy],zs,"as,as,fr" output should be

abc [def,ghi,ijk] lm (no,pq,rs) [tu,vw,xy] zs "as,as,fr"

I tried this str.replaceAll("\\(.*?\\)|(,)", " "); say my string is str, it will replace commas which are not inside ( ) but output will not have content inside ( )

Any help is highly appreciated

Upvotes: 2

Views: 1027

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174696

Use the below regex and then replace the matched comma with a space.

,(?=(?:"[^\["(){}\]]*"|\([^\["{}()\]]*\)|\[[^\["{}()\]]*\]|\{[^\["(){}\]]*}|[^"\[{}()\]])*$)

OR

,(?=(?:"[^"]*"|\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*}|[^"\[{}()\]])*$)

DEMO

String s = "\"f,g\",abc,[def,ghi,ijk],lm,(no,pq,rs),[tu,vw,xy],zs,\"as,as,fr\",foo,{bar,buz}";
System.out.println(s.replaceAll(",(?=(?:\"[^\\[\"(){}\\]]*\"|\\([^\\[\"{}()\\]]*\\)|\\[[^\\[\"{}()\\]]*\\]|\\{[^\\[\"(){}\\]]*}|[^\"\\[{}()\\]])*$)", " "));

Output:

"f,g" abc [def,ghi,ijk] lm (no,pq,rs) [tu,vw,xy] zs "as,as,fr" foo {bar,buz}

Explanation:

  • , Matches all the commas

  • ,(?= ONly if it's followed by,

  • "[^\["(){}\]]*" A double quotes block like "foo,bar"

  • | OR

  • \([^\["{}()\]]*\) paranthesis block like (foo,bar)

  • | OR

  • \[[^\["{}()\]]*\] a square bracket block like [foo,bar]

  • | OR

  • \{[^\["(){}\]]*} A curly brace block like {foo,bar}

  • | OR

  • [^"\[{}()\]] Any character but not of " or ( or ) or { or [ or ] or }.

  • zero or more times. This applies to the whole, that is like (foo,bar) may be repeated zero or more times.

  • $ Followed by an end of the line anchor.

Upvotes: 3

TheLostMind
TheLostMind

Reputation: 36304

Try regex like this :

public static void main(String... strings) {
    String s = "abc,[def,ghi,ijk],lm,(no,pq,rs),[tu,vw,xy],zs,\"as,as,fr\",xyz,pqr";
    String[] arr = s.split("(,(?![\\w,]+[\\]\\)\"]))|((?<=[\\]\"\\)]),)");
    for (String str : arr) {
        System.out.println(str);
    }
}

O/P :

abc
[def,ghi,ijk]
lm
(no,pq,rs)
[tu,vw,xy]
zs
"as,as,fr"
xyz
pqr

PS : The below code will work for single quotes and flower braces as well

String[] arr = s.split("(,(?![\\w,]+[^,\\w]))|((?<=[^,\\w]),)");

Upvotes: 0

vks
vks

Reputation: 67968

,(?![^\[({]*[\])}])(?![^"']*["'](?:[^"']*["'][^"']*["'])*[^"']*$)

This should work fine for you.The lookahead will make sure , is not between parenthesis or quotes.See demo.

https://regex101.com/r/jG2wO4/8

For java escape \ again.make it \\

Or if you can live with some extra spaces. try

(['"(\[{].*?['")}\]])|,

Replace by $1.See demo.

https://regex101.com/r/jG2wO4/7

Upvotes: 0

anubhava
anubhava

Reputation: 785058

Here is simpler regex for this. Match this regex:

(\[[^]]*\]|\([^)]*\)|"[^"]*"),?|,

And replace by:

"$1 "

RegEx Demo

Upvotes: 1

Related Questions