Java provides some useful character classes like \d and \w. Can I define my own character classes? For example, it would be useful to be able to define shorthands for character classes like [A-Za-z_].
Java provides some useful character classes like \d and \w . Can I define
Share
No, you can’t.
Personally, when I have a (slightly) complicated regex, I break the regex up in smaller sub-regexes and then “glue” them together with a
String.format(...)like this:which is far more readable than a single pattern:
Note that this is just a quick example: validating IP addresses can probably better be done by a class from the
java.netpackage, and if you’d do it like that, the pattern should be placed outside the method and pre-compiled.Be careful with
%signs inside your pattern!