0

I want to know the meaning of: (\\d{1,2})\\/(\\d{1,2})\\/(\\d{1,4})

I know "\d{1,2}" means "1 to 2 numbers", and "\/" means "/"

but I do not know what do the rest of the things mean. Why are there so many "\" ! It seams to me that it

should be "\/" instead of "\\/", and "\d" instead of "\\d"

I have run the program. It worked perfectly good. Below is a part of the program.

/** Constructs a Date object corresponding to the given string.
   *  @param s should be a string of the form "month/day/year" where month must
   *  be one or two digits, day must be one or two digits, and year must be
   *  between 1 and 4 digits.  If s does not match these requirements or is not
   *  a valid date, the program halts with an error message.
   */
  public Date(String s) {if (s.matches("(\\\d{1,2})\\\\/(\\\d{1,2})\\\\/(\\\d{1,4}) "))      //this is the first line of the 

object.

  }
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Becky
  • 3
  • 1
  • 4
  • Possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Kristján Oct 25 '15 at 03:42
  • In a Java String literal, the `\ ` character is an escape character, e.g. since Java strings start and end with `"`, any `"` characters in the string must be escaped as `\"`. This also applies to any `\ ` characters in the string, which must be given as `\\ `. That is why every `\ ` is doubled. – Andreas Oct 25 '15 at 03:43
  • Thank you very much. I got it ! O(∩_∩)O – Becky Oct 25 '15 at 03:59

1 Answers1

1

You are likely building the regular expression in a language, such as JavaScript, where the backslashes need to be escaped before they are interpreted as part of the regular expression.

In this situation \\d will reduce to a literal backslash followed by d (\d), which in turn will be evaluated as the term to find a digit.

If that's not clear, this question and its answers may further your understanding: Java Regex Escape Characters

Community
  • 1
  • 1
Joe DeRose
  • 3,438
  • 3
  • 24
  • 34