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 '-' } }
Bart Kiers Jul 05 2018-11-11T00: 00Z
source share