Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a String Into Multiple Strings Using a Regex With Different Capture Groups

Tags:

java

string

regex

I am trying to split a string into multiple strings but rather than using a string just one simple regex pattern, I am trying to use a regex pattern that will split a string into different strings if it detects certain characters, but the characters are different. Instead of splitting the string into different strings, it's giving me each and every individual characters in said string.

String[] splitstr = line.split("([&]{2})?([|]{2})?(!=)?");

Using the above line, I have a variable called line which, as an example, I am putting this line from a file:

:if[input=right || input=Right]:

I am just wondering if there is a way to make this split into

":if[input=right", "input=Right]:"

And if I put in a line like this:

:if[input=right || input=Right && input != null]:

So that it splits into

":if[input=right", "input=Right", "input != null]:"

I was using String#split(regex) for the || symbol and it worked just fine, but now that I want it to split wherever that are || or && or != and I want my code to be efficient and clean and easy to read.

like image 974
Alex Couch Avatar asked Oct 29 '22 05:10

Alex Couch


1 Answers

The java class below will split your example string into the parts you are interested in. The code will split the original string at all '||' and '&&' delimeters, globally. I.e, if you have more than one '||' or '&&' operator in your original string, each part will be split out.

One thing to note is the need to escape (\) the special characters. In Java you also need to escape the escape, so you need 2 backslashes in order to have a literal in your string.

Here's a great site to test out regEx code ... Regular Expressions 101

public class splitStrRegex {

    public static void main(String[] args) {

        String myStr = ":if[input=right || input=Right && input != null]:";
        String[] myStrings = myStr.split("\\|\\||&&");
        for(int i = 0; i < myStrings.length; i++) {
            System.out.println(myStrings[i].trim());
        }
    }
}

Output:

:if[input=right
input=Right
input != null]:
like image 148
MJFoster Avatar answered Nov 15 '22 06:11

MJFoster