0

Why does Pattern/Matcher work with (\\d+)([a-zA-Z]+) but String.split() doesn't ?

For example:

String line = "1A2B"; Pattern p = Pattern.compile("(\\d+)([a-zA-Z]+)"); Matcher m = p.matcher(line); System.out.println(m.groupCount()); while(m.find()) { System.out.println(m.group()); } 

Prints :

2 1A 2B 

But :

 String line = "1A2B"; String [] arrayOfStrings = line.split("(\\d+)([a-zA-Z]+)"); System.out.println(arrayOfStrings.length); for(String elem: arrayOfStrings){ System.out.println(elem); } 

Prints only:

0 
3
  • 1
    The regex in the case of split is a delimiter whereas in the case of matcher it's a "pattern" used to match your expression of choice... Commented Jan 6, 2015 at 15:26
  • You want to split according to what? Commented Jan 6, 2015 at 15:26
  • Just split into groups of (number+letter). But why can't I use the same regex with String.split() ? Commented Jan 6, 2015 at 15:30

2 Answers 2

1

That is because the .split(String regex) uses the regular expression to mark where to break the string. So, in your case, if you have 1A2B£$%^& it will print 1 string: £$%^& because it will split at 1A and then again at 2B, however, since those return empty groups, they are omitted and you are left with just £$%^&.

On the other hand, the regular expression does is that it matches the strings and puts them into groups. These groups can then be accessed at a later stage as you are doing.

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

Comments

1

Why it didnt work

Because the spit would consume those characters and there is no character left to be in the output list

Solution

Not perfect but look aheads will help you

String line = "1A2B"; String [] arrayOfStrings = line.split("(?=\\d+[a-zA-Z]+)"); System.out.println(arrayOfStrings.length); for(String elem: arrayOfStrings){ System.out.println(elem); 

will give output as

3 1A 2B 

Not perfect becuase the look ahead will be true at the start of the string, thus creating an empty string in the output list at index 0. In the example you can see that the length is 3 where as we expect 2

1 Comment

Oops sorry my bad. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.