[java] How to type ":" ("colon") in regexp?

: ("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.,-\:]*

This question is related to java regex

The answer is


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


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:

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.


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