Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string using Regex in Java

Tags:

java

regex

Would anyone be able to assist me with some regex.

I want to split the following string into a number, string number

"810LN15"

1 method requires 810 to be returned, another requires LN and another should return 15.

The only real solution to this is using regex as the numbers will grow in length

What regex can I used to accomodate this?

like image 545
Damien Avatar asked Apr 07 '11 13:04

Damien


People also ask

How do you split a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

Can we split string with in Java?

You can use the split() method of java. lang. String class to split a string based on the dot. Unlike comma, colon, or whitespace, a dot is not a common delimiter to join String, and that's why beginner often struggles to split a String by dot.

What does split () do in Java?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.


1 Answers

String.split won't give you the desired result, which I guess would be "810", "LN", "15", since it would have to look for a token to split at and would strip that token.

Try Pattern and Matcher instead, using this regex: (\d+)|([a-zA-Z]+), which would match any sequence of numbers and letters and get distinct number/text groups (i.e. "AA810LN15QQ12345" would result in the groups "AA", "810", "LN", "15", "QQ" and "12345").

Example:

Pattern p = Pattern.compile("(\\d+)|([a-zA-Z]+)");
Matcher m = p.matcher("810LN15");
List<String> tokens = new LinkedList<String>();
while(m.find())
{
  String token = m.group( 1 ); //group 0 is always the entire match   
  tokens.add(token);
}
//now iterate through 'tokens' and check whether you have a number or text
like image 55
Thomas Avatar answered Oct 19 '22 21:10

Thomas