2

I have a scenario where a user input can be an arabic date like ٢٠١٩-٠٣-٣٠ or normal date like 2019-07-31.

I am trying to find a regular expression which matches both cases

right now I am using the regex to match the arabic date with the one I got from here

my code is like

        String s1 = "٢٠١٩-٠٣-٣٠";
        String regx = "^[\\u0621-\\u064A\\u0660-\\u0669 ]+$";
        System.out.println(regx.matches(s1));

but its printing false, how can I fix it, also how can I add the normal date regex to this one ?

Markus Steppberger
  • 618
  • 1
  • 8
  • 18
robin
  • 1,893
  • 1
  • 18
  • 38

2 Answers2

2

You should call the matches method on a string and use regx as an argument, not the other way around. And you don't need to escape a backslash for unicode symbols. Also, add a dash and the "normal" (which are incidentally called "arabic") numerals into the regular expression, and you should get what you want:

String s1 = "٢٠١٩-٠٣-٣٠";
String s2 = "03-03-2019";
String regx = "^[\\-\u0621-\u064A\u0660-\u06690-9 ]+$";
System.out.println(s1.matches(regx));
System.out.println(s2.matches(regx));

Note that this regular expression only validates that the string consists of valid symbols, not that it has the right format.

Forketyfork
  • 7,416
  • 1
  • 26
  • 33
  • How can I use to convert s1 and s2 to LocaleDate ? – robin Mar 06 '19 at 16:47
  • @robin I believe parsing the string to a date is a different question, but it seems to be already answered here: https://stackoverflow.com/questions/4496359/how-to-parse-date-string-to-date – Forketyfork Mar 06 '19 at 16:49
  • My question is how can I use the same format to parse the dates s1 and s2 ? – robin Mar 06 '19 at 16:52
  • @robin You can't use the same format. You'd have to use something like `new SimpleDateFormat("yyyy-MM-dd", Locale.forLanguageTag("ar-SA-nu-arab"))` to parse the arabic-indic numerals, and `new SimpleDateFormat("dd-MM-yyyy")` to parse a regular date. – Forketyfork Mar 06 '19 at 17:02
0

You have to put the regex inside matches, so

s1.matches(regx);