Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Regex with OR condition to Split String

I need to build a regex to Split my string starting with a number or LM(exact match as it is a special case)

For example - 
Input : 1LM355PL6R5L8
Output : [1,LM,3,5,5PL,6R,5L,8]

Input : 349AB8LM7Y4II
Output : [3,4,9AB,8,LM,7Y,4II]

For numbers, i’ve build this regex (?<!^)(?=\\d) and it seems to be working fine.
Now i’m confused how to add this exact match of ‘LM’. It can be at any position

List<String> diff = Arrays.asList(inputString.split("(?<!^)(?=\\d)"));

Actual Output with above code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output : [1LM,3,5,5PL,6R,5L,8]
    
Output : [3,4,9AB,8LM,7Y,4II]

I’m trying to put an OR condition in my regex and make strict match for LM but not getting correct results from it.

List<String> diff = Arrays.asList(inputString.split("(?<!^)(?=\\d)|('LM')"));

>Solution :

The or part with | should be put inside the lookahead and there should not be quotes around LM.

inputString.split("(?<!^)(?=\\d|LM)")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading