简体   繁体   English

拆分不同长度的字符串

[英]Split the string with different length

I have a String String s = " ABCD 1122-12-12" , ie <space or single digit number>+<any string>+<space>+<date in YYYY-mm-dd> format.我有一个 String String s = " ABCD 1122-12-12" ,即<space or single digit number>+<any string>+<space>+<date in YYYY-mm-dd>格式的日期。

What could be the regex for String.split method or any other utility methods to split the above string into three parts String.split 方法或任何其他实用程序方法的正则表达式可以是什么来将上述字符串分成三部分

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

[1] = <string> = "ABCD"

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

The regex ( |\\d)(.+) (\\d{4}-\\d{2}-\\d{2}) should do the job.正则表达式( |\\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 + "'");
}

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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