Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

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

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}"
));
question from:https://stackoverflow.com/questions/1379191/why-does-this-java-regex-cause-illegal-escape-character-errors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...