• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using Reg Expressions in split  RSS feed

 
Ranch Hand
Posts: 1785
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to get the following code to split numbers and characters.

This works for strings like 4y, 2m but not for 99y

 
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The regular expression '[0-9]' will match a single numeric character. You need more information in the regular expression if the real pattern is more complex.

So what is the real pattern you are trying to match? How many digits can there be?
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is a very weird use of the split() method. Arguably, you are not even spitting at all.

You are using split to remove characters, leaving the numbers behind. And then, doing the same with numbers to leave the letters behind. The reason that it is not working for "99y" is because you are splitting on a single digit, which will leave the result in the third element (at index 2).

Henry
 
Steve Dyke
Ranch Hand
Posts: 1785
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:The regular expression '[0-9]' will match a single numeric character. You need more information in the regular expression if the real pattern is more complex.

So what is the real pattern you are trying to match? How many digits can there be?


Maximum of 2.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Them you can quantify the number of digits. Assuming there must be 1 or 2 digits you can add {1,2} to say the previous character or group can appear 1 or 2 times.

As Henry said, this is an unconventional use of the split method though. It would be more usual to have a single regular expression and use capture groups to extract the bits you're interested in.
 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree that split is not the right tool for the job. Use the regular expression API to grab the pieces-parts using grouping as Mike suggested.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!