Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Java regex cause "illegal escape character" errors?

Tags:

java

regex

I'm working on a solution to a previous question, as best as I can, using regular expressions. My pattern is

"\d{4}\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}" 

According to NetBeans, I have two illegal escape characters. I'm guessing it has to do with the \d and \w, but those are both valid in Java. Perhaps my syntax for a Java regular expression is off...

The entire line of code that is involved is:

userTimestampField = new FormattedTextField(   new RegexFormatter(     "\d{4}\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}" )); 
like image 422
Thomas Owens Avatar asked Sep 04 '09 13:09

Thomas Owens


People also ask

How do I stop illegal escape characters in Java?

Use "\\" to escape the \ character.

How do you escape a character in regex Java?

To escape a metacharacter you use the Java regular expression escape character - the backslash character. Escaping a character means preceding it with the backslash character. For instance, like this: \.

What is escaped character in regex?

? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters. Use a double backslash ( \\ ) to denote an escaped string literal.

What is regex \\ s in Java?

\\s - matches single whitespace character. \\s+ - matches sequence of one or more whitespace characters.


1 Answers

Assuming this regex is inside a Java String literal, you need to escape the backslashes for your \d and \w tags:

"\\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}" 

This gets more, well, bonkers frankly, when you want to match backslashes:

public static void main(String[] args) {             Pattern p = Pattern.compile("\\\\\\\\"); //ERM, YEP: 8 OF THEM     String s = "\\\\";     Matcher m = p.matcher(s);     System.out.println(s);     System.out.println(m.matches()); }  \\ //JUST TO MATCH TWO SLASHES :( true 
like image 79
butterchicken Avatar answered Sep 17 '22 15:09

butterchicken