为什么这个 Java 正则表达式会导致“非法转义字符”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1379191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:22:25  来源:igfitidea点击:

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

javaregex

提问by Thomas Owens

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

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

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

采纳答案by butterchicken

Assuming this regex is inside a Java Stringliteral, you need to escape the backslashes for your \dand \wtags:

假设这个正则表达式在 JavaString文字中,你需要为你的\d\w标签转义反斜杠:

"\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, bonkersfrankly, 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

回答by willcodejavaforfood

Did you try "\\d"and "\\w"?

你有没有尝试"\\d""\\w"

-edit- Lol I posted the right answer and get down voted and then I notice that stackoverflow escapes backslashes so my answer appeared wrong :)

-edit-大声笑我发布了正确的答案并被否决了然后我注意到stackoverflow转义反斜杠所以我的答案似乎是错误的:)

回答by MystikSpiral

I think you need to add the two escaped shortcuts into character classes. Try this: "[\d]{4}[\w]{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"

我认为您需要将两个转义快捷方式添加到字符类中。尝试这个: "[\d]{4}[\w]{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"

--Good Luck.

- 祝你好运。

回答by asalamon74

What about the following: \\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}

以下情况如何: \\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}

回答by Christopher Klewes

Have you tried this?

你试过这个吗?

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

回答by Daniel

all you need to do is to put

你需要做的就是把

 *\
 ex: string ex = 'this is the character: *\s';

before your invalid character and not 8 \ !!!!!

在您的无效字符之前而不是 8 \ !!!!!!