-2

I want to know if this is the right pattern for matches string like following

String samples

23.04.2019-30.04.2019
3.06.2019-20.06.2019

Pattern

private final Pattern TIMELINE_PATTERN = Pattern.compile("^\\d{2}.\\d{2}.\\d{4}-\\d{2}.\\d{2}.\\d{4}$");
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

2 Answers2

1

Two problems in your current regex,

  • First quantifier needs to be {1,2} instead of just {2} to support either one digit or two
  • You need to escape dot

The correct regex you need to use should be this,

^\d{1,2}\.\d{2}\.\d{4}-\d{2}\.\d{2}\.\d{4}$

Regex Demo

Java code,

List<String> list = Arrays.asList("23.04.2019-30.04.2019", "3.06.2019-20.06.2019");

list.forEach(x -> {
    System.out.println(x + " --> " + x.matches("^\\d{1,2}\\.\\d{2}\\.\\d{4}-\\d{2}\\.\\d{2}\\.\\d{4}$"));
});

Prints,

23.04.2019-30.04.2019 --> true
3.06.2019-20.06.2019 --> true
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
  • 2
    Presumably the day could be 1/2 digits in _either_ of the two dates. And also, `String#matches` implicitly puts anchors around the pattern, so using `^` and `$` in your code is redundant. – Tim Biegeleisen Apr 26 '19 at 09:59
  • @TimBiegeleisen: My regex was for the data he has given. But yes if other fields can have one or two digits, then we can use `{1,2}` there as well. – Pushpesh Kumar Rajwanshi Apr 26 '19 at 10:07
1

If the day/month components could be one or two digit characters, then you should use this pattern:

^\d{1,2}\.\d{1,2}\.\d{4}-\d{1,2}\.\d{1,2}\.\d{4}$

Demo

Presumably the years might also not be fixed width, but it is probably unlikely that a year earlier than 1000 would appear, so we can fix the year at 4 digits. Also, literal dot in a regex pattern needs to be escaped with a backslash.

Edit:

If you want to first validate the string, and then separate the two dates, then consider this:

String input = "3.06.2019-20.06.2019";
if (input.matches("\\d{1,2}\\.\\d{1,2}\\.\\d{4}-\\d{1,2}\\.\\d{1,2}\\.\\d{4}")) {
    String[] dates = input.split("-");
    System.out.println("date1: " + dates[0]);
    System.out.println("date2: " + dates[1]);
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360