7

I need to split a string where there's a comma, but it depends where the comma is placed.

As an example

consider the following:

C=75,user_is_active(A,B),user_is_using_app(A,B),D=78

I'd like the String.split() function to separate them like this:

C=75 

user_is_active(A,B) 

user_using_app(A,B)

D=78

I can only think of one thing but I'm not sure how it'd be expressed in regex.

The characters/words within the brackets are always capital. In other words, there won't be a situation where I will have user_is_active(a,b).

Is there's a way to do this?

3 Answers 3

12

If you don't have more than one level of parentheses, you could do a split on a comma that isn't followed by a closing ) before an opening (:

String[] splitArray = subjectString.split(
    "(?x),   # Verbose regex: Match a comma\n" +
    "(?!     # unless it's followed by...\n" +
    " [^(]*  # any number of characters except (\n" +
    " \\)    # and a )\n" +
    ")       # end of lookahead assertion");

Your proposed rule would translate as

String[] splitArray = subjectString.split(
    "(?x),        # Verbose regex: Match a comma\n" +
    "(?<!\\p{Lu}) # unless it's preceded by an uppercase letter\n" +
    "(?!\\p{Lu})  # or followed by an uppercase letter");

but then you would miss a split in a text like

Org=NASA,Craft=Shuttle
Sign up to request clarification or add additional context in comments.

3 Comments

this works prefect! I dont think I will have more than one level parentheses! thanks! :D
+1 And if the (A,B) construct will only ever have one comma inside, you can speed this up dramatically by adding a comma to the [^(]* expression i.e. [^(,]*.
in my case I could have something(A,B,C) so it wouldn't apply but it's good to know! thanks!
0

consider using a parser generator for parsing this kind of query. E.g: javacc or antlr

Comments

0

As an alternative, if you need more than one level of parentheses, you can create a little string parser for parsing the string character by character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.