在Java中使用正则表达式拆分字符串模式

时间:2013-07-04 08:07:52

标签: java regex string split

使用Regex我必须拆分字符串模式并展开它们。

例如:

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

但对于更复杂的字符串模式,如“rue-Richard 2-5”,我必须拆分并展开:

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

但对于另一个更复杂的字符串模式,如“rue-Richard 2,5,7,11”,我必须拆分并展开:

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

1 个答案:

答案 0 :(得分:0)

此处的正则表达式无济于事,因为您有两个任务要做:

  • 从数字中分隔非数字;
  • 分析数字。

一个简单的解决方案是使用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

然后你“只”必须分析数字部分。