Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining the split value after java string split

Tags:

java

split

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: >
like image 701
Phillip Avatar asked Sep 24 '18 10:09

Phillip


People also ask

How do you get the last index after the split?

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.

What happens when you split a string in Java?

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.

What does split method return?

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.

What is the return type of split () method of string class?

The return type of Split is an Array of type Strings.


1 Answers

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

like image 171
The fourth bird Avatar answered Oct 22 '22 05:10

The fourth bird