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

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

+45
java regex
Jul 05 2018-11-11T00:
source share
4 answers

In most regex implementations (including Java) : doesn’t matter much either inside or outside the character class.

Your problem is most likely due to the fact that - 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 ':' .

Try this instead:

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

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

Demonstration:

 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 '-' } } 
+86
Jul 05 2018-11-11T00:
source share

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

+7
Jul 05 2018-11-11T00:
source share

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

All characters other than alphanumeric characters than \ , - , ^ (at the beginning) and termination ] are not special to character classes, but this is not harmful if they are escaped.

For more information on Java regular expressions, see the docs .

+4
Jul 05 2018-11-11T00:
source share

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

+1
Jul 05 '11 at 8:40
source share



All Articles