为什么这个Java正则表达式导致“非法转义字符”?错误? [英] Why does this Java regex cause "illegal escape character" errors?

查看:846
本文介绍了为什么这个Java正则表达式导致“非法转义字符”?错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究解决上一个问题,尽我所能,使用正则表达式。我的模式是

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}"

根据NetBeans,我有两个非法的转义字符。我猜它与\d和\ w有关,但这些在Java中都是有效的。也许我的Java正则表达式的语法已关闭......

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...

涉及的整行代码是:

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}"
));


推荐答案

假设这个正则表达式在Java <$ c $中c> String literal,你需要转义 \d \w 标签:

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}"

当你想要的时候,坦率地说这会更好, bonkers 匹配反斜杠:

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

这篇关于为什么这个Java正则表达式导致“非法转义字符”?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆