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

JavaRegex

Java Problem Overview


: ("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 Solutions


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

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 '-'
    }
}

Solution 2 - Java

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

Solution 3 - Java

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.

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOleg VazhnevView Question on Stackoverflow
Solution 1 - JavaBart KiersView Answer on Stackoverflow
Solution 2 - JavaSteeveDrozView Answer on Stackoverflow
Solution 3 - Javauser456814View Answer on Stackoverflow
Solution 4 - JavaAnantha SharmaView Answer on Stackoverflow