2010-09-26 85 views
0

以下正則表達式在string.replaceall()中使用,但不適用於string.replaceFirst()。java 6 replaceall replacefirst

字符串:

TEST|X||Y|Z|| 

預期輸出:

TEST|X|**STR**|Y|Z|| 

正則表達式:

string.replaceAll("(TEST\\|[\\|\\|]*\\\\|)\\|\\|", "$1|ST|"); 


Output (not desired): 


TEST|X|**STR**|Y|Z|**STR**| 


string.replaceFirst("(TEST\\|[\\|\\|]*\\\\|)\\|\\|", "$1|ST|"); 

沒有任何調整串製成。

請幫忙!

在此先感謝。

回答

0

你的問題不是很清楚,但我假設你在問爲什麼在輸出中有差異。在字符串中傳遞的正則表達式模式有兩個匹配。所以,當你說replaceAll這兩個匹配被替換,並且當replaceFirst被使用時,只有第一個被替換。因此,輸出的差異。要找到匹配項 -

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Regex { 

    public static void main(String[] args) { 

     String string1 = new String("TEST|X||Y|Z||");   

     Pattern pattern = Pattern.compile("(TEST\\|[\\|\\|]*\\\\|)\\|\\|"); 
     Matcher matcher = pattern.matcher(string1); 

     boolean found = false; 
     while (matcher.find()) { 
      System.out.printf("I found the text \"%s\" starting at " 
        + "index %d and ending at index %d.%n", matcher.group(), 
        matcher.start(), matcher.end()); 
      found = true; 
     } 
     if (!found) { 
      System.out.printf("No match found.%n"); 
     } 
    } 
} 
+0

考慮的最後兩個「||」。它們在Z之前是如何匹配的?我沒有看到任何匹配的正則表達式。 – djna 2010-09-26 17:28:34

+0

@djna - 我沒有看到任何一個..我實際上是在跑代碼。 – 2010-09-26 17:36:10

+0

我認爲他的問題是他有一個意外的OR – djna 2010-09-26 17:47:23

0

如果您只想替換第一個「||」通過「| ST |」,你可以這樣做:

System.out.println("TEST|X||Y|Z||".replaceFirst("\\|\\|", "|ST|")); 
0

你的正則表達式可能沒有做你期望的。原因是管道符號|有兩個含義。這是你的分析師,也是正則表達式中的

(TEST\\|[\\|\\|]*\\\\|)\\|\\| 

您有效搜索測試等,或||並且都匹配|| s

如果你試圖只匹配||在TEST | X |之後你可以使用

"(TEST\\|[^\\|]*)\\|\\|" 

TEST其次是管道,其次零個或多個非管道,其次是兩個管道