:
("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.,-\:]*
In character class [-+_~. \d\w] : - means - + means +
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).
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.
In Java, "\b" is a back-space character (char 0x08 ), which when used in a regex will match a back-space literal.
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 '-' } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With