如何输入“:” regexp中的(“冒号”)? [英] How to type ":" ("colon") in regexp?
问题描述
:
(冒号)在regexp中有特殊含义,但我需要按原样使用它,如 [A-Za Z0-9, - :] *
。
我试图逃避它,但这不起作用 [A-Za-z0-9。, - \:] *
:
("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.,-\:]*
推荐答案
在大多数正则表达式实现(包括Java)中,:
没有特殊含义,也没有内部也不在字符类之外。
In most regex implementations (including Java's), :
has no special meaning, neither inside nor outside a character class.
您的问题很可能是因为 -
充当范围运算符在你班上:
Your problem is most likely due to the fact the -
acts as a range operator in your class:
[A-Za-z0-9.,-:]*
其中, - :
匹配之间的所有ascii字符,'
和':'
。请注意,它仍然与文字':'
相匹配!
where ,-:
matches all ascii characters between ','
and ':'
. Note that it still matches the literal ':'
however!
请改为尝试:
[A-Za-z0-9.,:-]*
通过在课程的开头或结尾放置 -
,它与文字 - 匹配
。正如Keoki Zee的评论中提到的,你也可以逃避课程中的 -
,但大多数人只是在最后添加它。
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.
演示:
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 '-'
}
}
这篇关于如何输入“:” regexp中的(“冒号”)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!