2

I want to split strings with regex java.
for example:

String: (5,4,a)

I want to split two String in following:

5 
4,a

if character is numeric after comma character do split
if character is letter after comma character do not split

I use of

[-|,]\\s*[^\\w] 

but do no right

1
  • 1
    Any attempts from your side ? Commented Dec 10, 2013 at 10:27

3 Answers 3

3

It is often better to not come up with a complex regex that "does it all". Just split on comma, then look if the last element is a number, if not you can still concatenate the second and thrid field again.

Sign up to request clarification or add additional context in comments.

2 Comments

I do agree, but in this case, the regex would not be that complex though.
@sp00m yes, but obviously complex enough to start a question on SO. When it comes to regexes I advocate extreme simplicity, because chances are high that next week you simply do not understand the regex you got from that SO guy.
2

You can use positive lookahead - a request that tells regex engine that a certain character must be there, but should not be consumed as part of the match:

"[()]|[,-](?=\\d)"

should do the job (demo on ideone). Above, (?=\\d) means "only if followed by a digit", without counting that digit as part of the match.

Comments

1

Try this out:

    String str = "5,4,c";
    // Just split the string into two parts
    String[] split = str.split(",", 2);

    System.out.println(split[0]);
    System.out.println(split[1]);

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.