I have an input string.
I am thinking how to match this string against more than one regular expression effectively.
Example Input: ABCD
I'd like to match against these reg-ex patterns, and return true
if at least one of them matches:
[a-zA-Z]{3} ^[^\\d].* ([\\w&&[^b]])*
I am not sure how to match against multiple patterns at once. Can some one tell me how do we do it effectively?
You can use alternation (|) operator to combine multiple patterns for your regexp. But in case you have various input and you will have to convert them to instance of Date from a string. Then you must follow in a sequence and validate the input one by one.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
Pattern. MULTILINE or (? m) tells Java to accept the anchors ^ and $ to match at the start and end of each line (otherwise they only match at the start/end of the entire string). Pattern.
$ means "Match the end of the string" (the position after the last character in the string).
If you have just a few regexes, and they are all known at compile time, then this can be enough:
private static final Pattern rx1 = Pattern.compile("..."), rx2 = Pattern.compile("..."), ...; return rx1.matcher(s).matches() || rx2.matcher(s).matches() || ...;
If there are more of them, or they are loaded at runtime, then use a list of patterns:
final List<Pattern> rxs = new ArrayList<>(); for (Pattern rx : rxs) if (rx.matcher(input).matches()) return true; return false;
you can make one large regex out of the individual ones:
[a-zA-Z]{3}|^[^\\d].*|([\\w&&[^b]])*
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