简体   繁体   中英

Splitting String pattern with Regex in Java

Using Regex I have to split String Patterns and expand them.

For Example:

String Pattern = "rue Richard2" -----> in 2 string 
Substring1 = "rue Richard" , Substring2 = "2"

But for more sophisticated String Pattern like "rue-Richard 2-5", I must split and Expand:

Substring1 = "rue-Richard " , Substring2 = "2"
Substring1 = "rue-Richard " , Substring2 = "3"
Substring1 = "rue-Richard " , Substring2 = "4"
Substring1 = "rue-Richard " , Substring2 = "5"

But for another more sophisticated String Pattern like "rue-Richard 2,5,7,11", I must split and Expand:

Substring1 = "rue-Richard." , Substring2 = "2"
Substring1 = "rue-Richard." , Substring2 = "5"
Substring1 = "rue-Richard." , Substring2 = "7"
Substring1 = "rue-Richard." , Substring2 = "11"

Regexes here won't help, since you have two tasks to do:

  • separate non-digits from digits;
  • analyze the digits.

An easy solution for this is to use Guava's CharMatcher :

// DIGIT matches all unicode digits, we don't want that
private static final CharMatcher DIGITS = CharMatcher.DIGIT
    .and(CharMatcher.ASCII);

// find first digit index
final int index = DIGITS.indexIn(input);
input.substring(0, index); // part without the digits
input.substring(index); // part with digits

Then you "only" have to analyze the digit part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM