分割不同长度的字符串

时间:2019-02-11 19:32:13

标签: java java-8

我有一个字符串String s = " ABCD 1122-12-12",即<space or single digit number>+<any string>+<space>+<date in YYYY-mm-dd>格式。

String.split方法或任何其他实用程序方法将上述字符串分成三部分的正则表达式是什么

[0] = <space or single digit number> = " "

[1] = <string> = "ABCD"

[2] = <date in YYYY-mm-dd> = "1122-12-12"

1 个答案:

答案 0 :(得分:0)

正则表达式( |\d)(.+) (\d{4}-\d{2}-\d{2})应该可以完成工作。

String input = " ABCD 1122-12-12";
Pattern pattern = Pattern.compile("( |\\d)(.+) (\\d{4}-\\d{2}-\\d{2})");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
  String spaceOrDigit = matcher.group(1);
  String string = matcher.group(2);
  String date = matcher.group(3);
  System.out.println("spaceOrDigit = '" + spaceOrDigit + "'");
  System.out.println("string = '" + string + "'");
  System.out.println("date = '" + date + "'");
}

输出:

spaceOrDigit = ' '
string = 'ABCD'
date = '1122-12-12'