2

How can I split a string A000101 as A000 and 101 , 000101 as 000 and 101 using the same regular expression.

I tried with something like this "A000101".split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)&(?!=0)") but output is A and 000101

edit :

Can I get A0000 and 0 from A00000 using the same logic ?

4
  • Is split mandatory? Why not use a Matcher with capturing groups? "([^1-9]*)([1-9]\\d*)"
    – dotvav
    Aug 25, 2015 at 8:41
  • I need to generate a series between two strings. My idea is to split up and increment the integer part
    – manoj
    Aug 25, 2015 at 8:44
  • Use split when you face a simple delimiter (comma, semicolon etc).
    – Stephan
    Aug 25, 2015 at 9:02
  • Java allows finite repitition in lookbehind, try (?<=^[^1-9]{1,11})(?=[1-9]) where 11 to be replaced with max num of characters that could occure before split-border.
    – Jonny 5
    Aug 25, 2015 at 9:04

2 Answers 2

2

It seems easier to me to use a Matcher instead of split:

String str = "A000101";
Pattern p = Pattern.compile("([^1-9]*)([1-9]\\d*)");
Matcher m = p.matcher(str);
if (m.matches()) {
    String prec = m.group(1);
    String post = m.group(2);
}
1

You may try this pattern as well:

([^0]*0*)(\d+)

Each group should give you one part of the string that you want in split.

Demo

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.