Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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

like image 403
Oleg Vazhnev Avatar asked Jul 05 '11 08:07

Oleg Vazhnev


People also ask

How do you write a colon in regex?

In character class [-+_~. \d\w] : - means - + means +

How do you type special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is ?: In regex?

It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.

What does \b mean in regex Java?

In Java, "\b" is a back-space character (char 0x08 ), which when used in a regex will match a back-space literal.


1 Answers

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

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

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.

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 '-'     } } 
like image 139
Bart Kiers Avatar answered Sep 22 '22 12:09

Bart Kiers