-4

I have the following Regex:

^\d{4}$

I want to use it as a pattern in Java, for example:

"add year ^\d{4}$"

But I get an error because it contains a backslash. How can I ignore that?

daiscog
  • 11,441
  • 6
  • 50
  • 62

2 Answers2

1

In Java strings, you have to escape the backslash:

"add year ^\\d{4}$"
jqno
  • 15,133
  • 7
  • 57
  • 84
  • when i do it this way the year string does not match it – Rashad Ahmad Feb 13 '17 at 12:18
  • The `^` matches the start of the input, so to have it in the middle of the string is probably what causes it not to match. You can try `"add year \\d{4}"`. – jqno Feb 13 '17 at 12:20
1

As jqno stated, you need to escape the backslash. But there is another problem in your regex. ^ means beginning of the string. So, you are actually looking for add year [beginning of the string]\d{4}[end of the string].

Use this instead:

"add year \\d{4}$"
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87