在 Java 正则表达式中,如何获取字符类(例如 [az])以匹配 - 减号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/154031/
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-10-29 11:13:30  来源:igfitidea点击:

In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign?

javaregex

提问by daveb

Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails

Is it possible to have the character class match a "-" ?

是否可以让字符类匹配“-”?

回答by Tomalak

Don't put the minus sign between characters.

不要在字符之间放置减号。

"[a-z-]"

回答by albertein

Escape the minus sign

转义减号

[a-z\-]

回答by codaddict

Inside a character class [...]a -is treated specially(as a range operator) ifit's surrounded by characters on both sides. That means if you include the -at the beginning or at the end of the character class it will be treated literally(non-special).

如果字符类[...]a-被两边的字符包围,它在内部被特殊对待(作为范围运算符)。这意味着如果您-在字符类的开头或结尾包含 ,它将按字面意思处理(非特殊)。

So you can use the regex:

所以你可以使用正则表达式:

^[a-z-]+$

or

或者

^[-a-z]+$

Since the -that we added is being treated literally there is no need to escape it. Although it's not an error if you do it.

因为-我们添加的 是按字面处理的,所以没有必要逃避它。虽然如果你这样做,这不是一个错误。

Another (less recommended) way is to not include the -in the character class:

另一种(不太推荐)的方法是不在-字符类中包含 :

^(?:[a-z]|-)+$

Note that the parenthesis are not optional in this case as |has a very low precedence, so with the parenthesis:

请注意,在这种情况下,括号不是可选的,因为|优先级非常低,因此使用括号:

^[a-z]|-+$

Will match a lowercase alphabet at the beginning of the string and one or more -at the end.

将匹配字符串开头的小写字母和-结尾的一个或多个。

回答by John M

I'd rephrase the "don't put it between characters" a little more concretely.

我会更具体地重新表述“不要把它放在字符之间”。

Make the dash the first or last character in the character class. For example "[-a-z1-9]" matches lower-case characters, digits or dash.

使破折号成为字符类中的第一个或最后一个字符。例如“[-a-z1-9]”匹配小写字符、数字或破折号。

回答by Michael Easter

This works for me

这对我有用

   Pattern p = Pattern.compile("^[a-z\-]+$");
   String line = "abc-def";
   Matcher matcher = p.matcher(line);
   System.out.println(matcher.matches());  // true