java - Can I define custom character class shorthands? -
java provides useful character classes \d
, \w
. can define own character classes? example, useful able define shorthands character classes [a-za-z_]
.
can define own character classes?
no, can't.
personally, when have (slightly) complicated regex, break regex in smaller sub-regexes , "glue" them string.format(...)
this:
public static boolean isvalidip4(string address) { string block_0_255 = "(0|[1-9]\\d|2[0-4]\\d|25[0-5])"; string regex = string.format( "%s(\\.%s){3}", block_0_255, block_0_255 ); return address.matches(regex); }
which far more readable single pattern:
"(0|[1-9]\\d|2[0-4]\\d|25[0-5])(\\.(0|[1-9]\\d|2[0-4]\\d|25[0-5])){3}"
note quick example: validating ip addresses can better done class java.net
package, , if you'd that, pattern should placed outside method , pre-compiled.
be careful %
signs inside pattern!
Comments
Post a Comment