Obtaining the split value after java string split

Phillip :

I have a string that is dynamially generated.

I need to split the string based on the Relational Operator.

For this I can use the split function.

Now I would also like to know that out of the regex mentioned above, based on which Relational Operator was the string actually splitted.

An example, On input

String sb = "FEES > 200";

applying

List<String> ls =  sb.split(">|>=|<|<=|<>|=");
System.out.println("Splitted Strings: "+s);

will give me the result,

Splitted strings: [FEES ,  200 ]

But expecting result:

Splitted strings: [FEES ,  200 ]
Splitted Relational Operator: >
The fourth bird :

You could use 3 capturing groups with an alternation for the second group:

(.*?)(>=|<=|<>|>|<)(.*)

Regex demo

Explanation

  • (.*?) Match any character zero or more times non greedy
  • (>=|<=|<>|>|<) Match either >= or <= or <> or > or <
  • (.*) Match any character zero or more times

For example:

String regex = "(.*?)(>=|<=|<>|>|<)(.*)";
String string = "FEES >= 200";            
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
if(matcher.find()) {
    System.out.println("Splitted Relational Operator: " + matcher.group(2));
    System.out.println("Group 1: " + matcher.group(1) + " group 3: " + matcher.group(3));
}

Demo java

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36803&siteId=1