user1668653
user1668653

Reputation: 237

Regarding Regex in java

I have a string as below.

   $x:Test( (x==5 || y==4) && ( (r==9 || t==10) && ( n>=2 || t<=4))) demo program 

In the above string the number of left and right paranthesis's will be changed based on the condition.

My requirement is whenever i encounter last right paranthesis then need to concatenate the below string.

 from "stream"

So the result will be as below.

$x:Test( (x==5 || y==4) && ( (r==9 || t==10) && ( n>=2 || t<=4))) from "stream" demo program 

To achieve this i am trying with the following code in java.

Pattern pattern = Pattern.compile(".*?\\.Event\\(([^\\(]*?|\\([^\\)]*?\\))*\\)");

if(line.matches(".*\\.Test(.*).*")){
    line = pattern.matcher(line).replaceAll("$0 from  \""+"stream"+"\""+" ");                 
}

But the above code is not working if the number of left and right paranthesis are more than 5 .

Need pointers to acheive the desired result i mean i need generic solution for any number of left and right parantheses.

Upvotes: 0

Views: 88

Answers (5)

Yogendra Singh
Yogendra Singh

Reputation: 34367

You may want to use lastIndexOf() and substring() functions as below:

String text = 
  "$x:Test( (x==5 || y==4) && ( (r==9 || t==10) && ( n>=2 || t<=4))) demo program";

int lastIndex = text.lastIndexOf(")");
String updatedText = 
        text.substring(0,lastIndex)+" from \"stream\""+text.substring(lastIndex+1);

EDIT: use replaceAll to replace all occurrences of ))) with ))) from "stream" as below:

 String text = 
  "$x:Test( (x==5 || y==4) && ( (r==9 || t==10) && ( n>=2 || t<=4))) demo program";

 String updatedText = text.replaceAll("\\)\\)\\)", "\\)\\)\\) from \"stream\"");

Upvotes: 0

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31428

The .* is greedy in Regex, thus search for ^(.*\))(.*) and replace with $1 from \"stream\"$2.

Upvotes: 0

Keppil
Keppil

Reputation: 46209

To get it after the rightmost parantheses, you can just use replaceFirst() like this:

String data = "   $x:Test( (x==5 || y==4) && ( (r==9 || t==10) && ( n>=2 || t<=4))) demo program ";
data = data.replaceFirst("^(.*\\))([^)]*)$", "$1 from \"stream\"$2");

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272237

Can you use String.lastIndexOf() ?

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213213

Why would you like to do it with Regex? Just use simple String class methods - String#lastIndexOf and String#substring to approach the problem: -

String str = "$x:Test( (x==5 || y==4) && ( (r==9 || t==10) && " + 
             "( n>=2 || t<=4))) demo program";

int index = str.lastIndexOf(")");
str = str.substring(0, index + 1) + " from \"stream\"" + 
      str.substring(index + 1);

Regexp is a very powerful language, but is really not required for something like this, where you are sure that where you need to split your string.

Upvotes: 5

Related Questions