Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a string against multiple regex patterns

Tags:

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?

like image 590
Patan Avatar asked Mar 07 '14 14:03

Patan


People also ask

How do you do multiple regex?

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.

How do I match a regex pattern?

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 "@" .

What is multiline pattern match?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


Video Answer


2 Answers

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; 
like image 132
Marko Topolnik Avatar answered Nov 16 '22 17:11

Marko Topolnik


you can make one large regex out of the individual ones:

[a-zA-Z]{3}|^[^\\d].*|([\\w&&[^b]])* 
like image 26
vandale Avatar answered Nov 16 '22 18:11

vandale