Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you match multiple Regex patterns for a single line of text in Java?

Tags:

java

regex

Lets say I have multiple patterns P1, P2, P3,, and so on. These patterns are different Regex patterns to match different variations of DATE.

How do I match these for the same input text most efficiently in a piece of code.

Of course, I can write a for() to loop over these patterns one by one, but is there a better way to do this?

like image 229
London guy Avatar asked May 08 '14 08:05

London guy


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.

What is multiline in regex?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.

How do you match line breaks in regex?

If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”. Whether or not you will have line breaks in your expression depends on what you are trying to match. Line breaks can be useful “anchors” that define where some pattern occurs in relation to the beginning or end of a line.


1 Answers

I think you can use the | operator of the regex and put the different regexes in paranthesis to be considered one whole regex to be matched.

("(P1)|(P2)|(P3)")

like image 64
anirudh Avatar answered Sep 24 '22 09:09

anirudh