-2

I have a String String s = " ABCD 1122-12-12", i.e <space or single digit number>+<any string>+<space>+<date in YYYY-mm-dd> format.

What could be the regex for String.split method or any other utility methods to split the above string into three parts

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

[1] = <string> = "ABCD"

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

  • Possible duplicate of [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – ferpel Feb 11 '19 at 19:37
  • Regex would be nuking the mosquito. Just use the `charAt`, `substring` and `lastIndexOf` methods. – Dawood ibn Kareem Feb 11 '19 at 19:38
  • Would not (\s|\d)(.+)\s+(\d\d\d\d-\d\d-\d\d) do? https://www.freeformatter.com/java-regex-tester.html – Michal Feb 11 '19 at 19:46

1 Answers1

0

The regex ( |\d)(.+) (\d{4}-\d{2}-\d{2}) should do the job.

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'
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56