Abhishek Jain
Abhishek Jain

Reputation: 4518

Greedy search for string patterns using regular expressions in Java

I have a use case where I want to search for a operator amongst <,>,<=,>=, and = in a given string and split the expression into 2 parts i.e. the right expression and the left expression and evaluate them individually before evaluating the final conditional operator.

This can be understood from the example below:

Pattern pattern1 = Pattern.compile("(.*?)(<|>|<=|=|>=)(.*)");
Matcher matcher2 = pattern1.matcher("4>=5");
while (matcher2.find()) {
        System.out.println(matcher2.group(1) + ";" + matcher2.group(2)+ ";" + matcher2.group(3));
}

Output:

4;>;=5

The expected output was 4;>=;5 but the >= operator got split because of the presence of the operator > independently.

I want to evaluate the clause (<|>|<=|=|>=) in a greedy fashion so that >= gets treated as a single entity and gets listed down if they occur together.

Upvotes: 1

Views: 249

Answers (2)

shyam
shyam

Reputation: 9368

you can try simplifying to

 pattern1 = Pattern.compile("(.*?)(>=?|<=?|=)(.*)");

Upvotes: 2

Javier Diaz
Javier Diaz

Reputation: 1830

String testt = "4>=5";
System.out.println(testt.replaceAll("(.*?)(>=?|<=?|=)(.*)", "$1;$2;$3"));

Easy to understand and you will replace all at once. You had a mistake that would stop getting <= if it finds a < before it, so just place those 2 <= and >= to the first places.

Upvotes: 1

Related Questions