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

后端 未结 5 1618
小鲜肉
小鲜肉 2020-12-17 09:05

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

5条回答
  •  不知归路
    2020-12-17 09:40

    To complement the other answers...

    You can write one big, hard-to-read pattern using the alternation operator:

    r1|r2|r3|...|rn
    

    where r1 etc are themselves "fully-fleged" regexes.

    However you have to be careful about the order of alternations: the first to match wins. That is, if the regex engine is not a POSIX regex engine but java.util.regex's engine isn't.

    Therefore, with text catflap, using regex:

    cat|catflap
    

    Java will match cat; a POSIX regex engine will match catflap (the longest, leftmost match).

    Sticking with more individual, maintainable patterns is imho a better option.

提交回复
热议问题