Becky
Becky

Reputation: 3

java regex: (\\d{1,2})\\/(\\d{1,2})\\/(\\d{1,4})

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.

  }

Upvotes: 0

Views: 7826

Answers (1)

Joe DeRose
Joe DeRose

Reputation: 3558

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

Upvotes: 1

Related Questions