HB.
HB.

Reputation: 35

Split the string at the particular occurrence of special character (+) using regex in Java

I want to split the following string around +, but I couldn't succeed in getting the correct regex for this.

String input = "SOP3a'+bEOP3'+SOP3b'+aEOP3'";

I want to have a result like this

 [SOP3a'+bEOP3', SOP3b'+aEOP3']

In some cases I may have the following string

c+SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2

which should be split as

[c, SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2] 

I have tried the following regex but it doesn't work.

input.split("(SOP[0-9](.*)EOP[0-9])*\\+((SOP)[0-9](.*)(EOP)[0-9])*");

Any help or suggestions are appreciated.

Thanks

Upvotes: 0

Views: 153

Answers (2)

m87
m87

Reputation: 4523

You can use the following regex to match the string and by replacing it using captured group you can get the expected result :

(?m)(.*?)\+(SOP.*?$)

see demo / explanation

Following is the code in Java that would work for you:

public static void main(String[] args) {
    String input = "SOP3a'+bEOP3'+SOP3b'+aEOP3'";
    String pattern = "(?m)(.*?)\\+(SOP.*?$)";

    Pattern regex = Pattern.compile(pattern);

    Matcher m = regex.matcher(input);
    if (m.find()) {
        System.out.println("Found value: " + m.group(0));
        System.out.println("Found value: " + m.group(1));
        System.out.println("Found value: " + m.group(2));
    } else {
        System.out.println("NO MATCH");
    }
}

The m.group(1) and m.group(2) are the values that you are looking for.

Upvotes: 1

Patrick Bard
Patrick Bard

Reputation: 1845

Do you really need to use split method? And what are the rules? They are unclear to me.

Anyway, considering the regex you provided, I've only removed some unnecessary groups and I've found what you are looking for, however, instead of split, I just joined the matches as splitting it would generate some empty elements.

const str = "SOP1a+bEOP1+SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2";
const regex = RegExp(/(SOP[0-9].*EOP[0-9])*\+(SOP[0-9].*EOP[0-9])*/)
const matches = str.match(regex);

console.log('Matches ', matches);
console.log([matches[1],matches[2]]);

Upvotes: 1

Related Questions