Get split value after Java string splitting

I have a dynamically generated string

I need to split the string according to the relational operator

To do this, I can use the split function

Now I also want to know which relational operator is the actual split string based on the regular expression mentioned above

An example in the input

String sb = "FEES > 200";

application

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

Will give me results,

Splitted strings: [FEES,200 ]

But expect results:

Splitted strings: [FEES,200 ]
Splitted Relational Operator: >

Solution

You can use 3 capture groups and change for the second group:

(*?) (greater than = | < = | < > | ≤) (*)

Regex demo

explain

>(.*?) Match any character zero or more times non greedy > (> = |< = |< > |<) match > = 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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>