Reputation: 237
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
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
Reputation: 31428
The .* is greedy in Regex, thus search for ^(.*\))(.*)
and replace with $1 from \"stream\"$2
.
Upvotes: 0
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
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