Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the regular expression [1-57-9] interpreted?

This is in Java: [1-57-9]

I came across this regular expression today, and I am trying to find out what it means exactly. Can anyone help me here?

like image 546
Black Magic Avatar asked Dec 05 '25 06:12

Black Magic


2 Answers

It's allowing the digits 1-5 and 7-9. So it's equivalent to [12345789].

See the docs for Pattern for the details of regular expressions in Java, in particular the examples under "Character classes":

  • [abc] - a, b, or c (simple class)
  • [^abc] - Any character except a, b, or c (negation)
  • [a-zA-Z] - a through z or A through Z, inclusive (range)
  • [a-d[m-p]] - a through d, or m through p: [a-dm-p] (union)
  • [a-z&&[def]] - d, e, or f (intersection)
  • [a-z&&[^bc]] - a through z, except for b and c: [ad-z] (subtraction)
  • [a-z&&[^m-p]] - a through z, and not m through p: [a-lq-z] (subtraction)

See also the regular-expressions.info web site, and its section on character classes.

like image 81
Jon Skeet Avatar answered Dec 07 '25 01:12

Jon Skeet


Read [1-57-9] as "1 to 5 or 7 to 9"

It matches a digit in 1, 2, 3, 4, 5, 7, 8, 9.

like image 29
ATOzTOA Avatar answered Dec 07 '25 01:12

ATOzTOA