2012-10-30 50 views
0

我有一個字符串,如下所示。關於java中的正則表達式

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

在上面的字符串中,根據條件將會更改左側和右側版本的數量。

我的要求是每當我遇到最後一個正確的palenthesis然後需要連接下面的字符串。

from "stream" 

所以結果如下。

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

爲了實現這一點,我嘗試用下面的代碼在java中。

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

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

但是,如果左側和右側paranthesis的數量大於5,上述代碼不起作用。

需要指針才能達到預期的結果我的意思是我需要任何數量的左和右的通用解決方案。

+0

@ user1668653 ..記住[將其中一個答案標記爲已接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) –

回答

5

你爲什麼想用正則表達式來做?只需使用簡單的String類方法 - String#lastIndexOfString#substring來解決這個問題: -

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是一個非常強大的語言,但確實不需要這樣的事情,你確信你需要拆分哪裏你的字符串。

+0

你是對的,但是問題是可能有兩個三個子字符串像$ x:Test((x == 5 || y == 4)&&((r == 9 || t == 10)&&「+ 」 ((x> 5 || y == 4)&&((r == 9 || t == 10)&&(&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 「+ 」(n> = 2 || t <= 4)))演示程序。在這種情況下,我需要將字符串「from stream」添加到$ x:Test(****)和$ x:示例(****)。這就是我使用正則表達式的原因。 – user1668653

+0

@ user1668653。這完全不是你原來的問題所說的,請發佈你期望的所有可能的輸入和輸出 –

+0

@ user1668653。你有這種感覺ituation,那麼'正則表達式'也不是你想要的。'正則表達式'在匹配'開放和關閉'括號方面不太好。 –

1

到最右邊括號後得到它,你可以只使用replaceFirst()這樣的:

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"); 
0

您可能需要使用lastIndexOf()substring()如下功能:

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); 

編輯:使用replaceAll來替換所有出現的)))))) from "stream",如下所示:

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

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

問題是可能有兩個三個子字符串像$ x:Test((x == 5 || y == 4)&&((r == 9 || t == 10)&&「+」 ((x> 5 || y == 4)&&((r == 9 || t == 10)&&(&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 「+」(n> = 2 || t <= 4)))演示程序。在這種情況下,我需要將字符串「from stream」添加到$ x:Test(*)和$ x:Sample(*) 。這就是我使用正則表達式的原因 – user1668653

+0

@ user1668653你的意思是,在同一個字符串中,你可能有更多的')))''''的實例,並且你想用'))流「'? –

+0

是的,你是對的 – user1668653

0

*。在正則表達式中貪婪,因此搜索^(.*\))(.*)並替換爲$1 from \"stream\"$2