Search code examples
javaregexpattern-matchingtext-extraction

Mandate a group inside regex OR group


I want to match alphanumeric characters and it must contain digits compulsorily. Basically, I want to extract an order number which is a combination of alphabets, digits and a few special characters. I wrote the following regex

String invoiceRegex = "(?<=((?i)(PO|P/O|ORDER)([\\s|.]{0,4})(number|no)?[|: -.]{0,10}))([\\dA-Z:-]*)";

But then it matches the invalid information such as IMMEDIATELY and other words. So I want a regex that matches alphanumeric characters with digits mandatory.

ex: From text "P/O No. : P9:8774" i want P9:8774.


Solution

  • I solved the problem.I made a group with alphabets an option and digit mandatory.and then repeated this group with +.

    now it looks something like this. an

    String invoiceRegex = "(?<=((?i)(PO|P/O|ORDER)([\\s|.]{0,4})(number|no)?[|: -.]{0,10}))([A-Z:-]*\\d+)+";