Java 如何在正则表达式中键入“:”(“冒号”)?

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

How to type ":" ("colon") in regexp?

javaregex

提问by javapowered

:("colon") has a special meaning in regexp, but I need to use it as is, like [A-Za-z0-9.,-:]*. I have tried to escape it, but this does not work [A-Za-z0-9.,-\:]*

:(“冒号”)在正则表达式中具有特殊含义,但我需要按原样使用它,例如[A-Za-z0-9.,-:]*. 我试图逃避它,但这不起作用[A-Za-z0-9.,-\:]*

采纳答案by Bart Kiers

In most regex implementations (including Java's), :has no special meaning, neither inside nor outside a character class.

在大多数正则表达式实现(包括 Java 的)中,:在字符类内部或外部都没有特殊含义。

Your problem is most likely due to the fact the -acts as a range operator in your class:

您的问题很可能是由于-它在您的班级中充当范围运算符:

[A-Za-z0-9.,-:]*

where ,-:matches all ascii characters between ','and ':'. Note that it still matches the literal ':'however!

where,-:匹配','和之间的所有 ascii 字符':'。请注意,它仍然与文字匹配':'

Try this instead:

试试这个:

[A-Za-z0-9.,:-]*

By placing -at the start or the end of the class, it matches the literal "-". As mentioned in the comments by Keoki Zee, you can also escape the -inside the class, but most people simply add it at the end.

通过放置-在类的开头或结尾,它与文字"-". 正如 Keoki Zee 的评论中提到的,你也可以-在 class 内部转义,但大多数人只是在最后添加它。

A demo:

一个演示:

public class Test {
    public static void main(String[] args) {
        System.out.println("8:".matches("[,-:]+"));      // true: '8' is in the range ','..':'
        System.out.println("8:".matches("[,:-]+"));      // false: '8' does not match ',' or ':' or '-'
        System.out.println(",,-,:,:".matches("[,:-]+")); // true: all chars match ',' or ':' or '-'
    }
}

回答by javapowered

Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:

冒号在字符类中没有特殊意义,不需要转义。根据PHP regex docs,字符类中唯一需要转义的字符如下:

All non-alphanumeric characters other than \, -, ^(at the start) and the terminating ]are non-special in character classes, but it does no harm if they are escaped.

除了\, -, ^(在开始处)和终止符之外的所有非字母数字字符]在字符类中都是非特殊的,但如果它们被转义也没有坏处。

For more info about Java regular expressions, see the docs.

有关 Java 正则表达式的更多信息,请参阅文档

回答by Anantha Sharma

use \\:instead of \:.. the \has special meaning in java strings.

使用\\:而不是\:..\在 java 字符串中具有特殊含义。

回答by SteeveDroz

Be careful, -has a special meaning with regexp. In a [], you can put it without problem if it is placed at the end. In your case, ,-:is taken as from ,to :.

小心,-与正则表达式有特殊含义。在 a 中[]如果将其放在最后,则可以毫无问题地放置它。在你的情况下,,-:被视为,: