5

I have String like this: "LODIXAL COMP 15"

How can i split it to "LODIXAL COMP" and "15" ?

String a = "LODIXAL COMP 15";

String[] result = {"LODIXAL COMP" , "15"}
3
  • Please read this Commented Jan 12, 2012 at 14:56
  • 3
    What's the exact criterion for the location of the split? Can the first returned string ever contain digits? Commented Jan 12, 2012 at 14:56
  • answerering on @aix's question will help create good answer to you. What you want to get for: AAA BBB 2 3 CCC 4? [AAA BBB, 2, 3, CCC, 4]? Commented Jan 12, 2012 at 15:25

1 Answer 1

14

Use this positive lookahead based regex:

a.split(" (?=\\d+)");

TESTING:

System.out.println(Arrays.toString(a.split(" (?=\\d+)")));

OUTPUT:

[LODIXAL COMP, 15]
Sign up to request clarification or add additional context in comments.

7 Comments

what with String a = "LODIXAL 12 3 COMP 15"; Output: [LODIXAL, 12, 3 COMP, 15]
@smas Yes this regex will not work with your string, you will need a.split(" (?=\\d+$)") for that. I can edit the answer but we don't know if OP can have string like that in his/her code.
there is other situation like this: String a = "ACEDICON COMP 1 X 5 MG" and it should be splits to "ACEDICON COMP 1" and "X 5 MG". How can i do it?
That can also be potentially done but IMHO that is very different problem than your original question. Why not ask a new question with that string and all of their variants. You will get much better answers that way.
For eg: you can use a.split(" (?=X\\s*\\d+)"); for your string "ACEDICON COMP 1 X 5 MG"
|

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.