简体   繁体   中英

Java Splitting Strings with several conditions

I want to split a string along several different conditions - I understand there is a Java String method called String.split(element), which splits the String into an array based on the element specified.

However, splitting among more objects seems to be very complex -- especially if the split must occur to a range of elements.

Precisely, I want java to split the string

  • "a>=b" into {"a",">=","b"}

  • "a>b" into {"a", ">", "b"}

  • "a==b" into {"a","==","b"}

I have been fiddling around with regex too just to see how to split it exactly based on this parameters, but the closest I've gotten is just splitting along a single character.

EDIT: a and b are arbitrary Strings that can be of any length. I simply want to split along the different kinds of comparators ">",">=","==";

For example, a could be "Apple" and b could be "Orange".

So in the end I want the String from "Apple>=Orange" into {"Apple", ">=", "Orange"}

You can use regular expressions. No matter if you use a, or b or abc for your variables you'll get the first variable in the group 1, the condition in the group 2 and the second variable in the group 3.

    Pattern pattern = Pattern.compile("(\\w+)([<=>]+)(\\w+)");
    Matcher matcher = pattern.matcher("var1>=ar2b");

    if(matcher.find()){
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
        System.out.println(matcher.group(3));
    }

The following code works for your examples:

System.out.println(Arrays.asList("a<=b".split("\\b")));

It splits the string on word boundaries.

If you need more elaborate splitting, you have to provide more examples.

You could code it out by hand and use whichever tokens you want to split on like so

public String[] splitString(String word)
{
    String[] pieces;
    String[] tokens = {"==", ">=", "<=","<", ">"};
    for(int i = 0; i < tokens.length; i++)
    {
        if(a.contains(tokens[i]))
        {
            pieces = {
                    word.substring(0, word.indexOf(tokens[i])), 
                    tokens[i], 
                    word.substring(word.indexOf(tokens[i]) + tokens[i].length(), word.length())};
            return pieces;
        }
    }
    return pieces;
}

This will return an array with whatever is before the token found, the token itself and whatever is left.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM