[英]In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign?
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 "-" ?是否可以让字符类匹配“-”?
不要在字符之间放置减号。
"[a-z-]"
转义减号
[a-z\\-]
Inside a character class [...]
a -
is treated specially(as a range operator) if it's surrounded by characters on both sides.在字符类
[...]
a -
两边都被字符包围,则它会被特殊对待(作为范围运算符)。 That means if you include the -
at the beginning or at the end of the character class it will be treated literally(non-special).这意味着如果您在字符类的开头或结尾包含
-
它将按字面意思处理(非特殊)。
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.将匹配字符串开头的小写字母和结尾的一个或多个
-
。
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]”匹配小写字符、数字或破折号。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.