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: >
To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.
The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.
The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
The return type of Split is an Array of type Strings.
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 timesFor 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With