2014-10-11 50 views
-1

請幫助我們,我想知道如何編寫正則表達式代碼。在java中編寫正則表達式代碼

可以說,一個文件包含3句

[hi Tom how are you.hey Andy its nice to see you.where is your wife Tom.] 

所以,當我搜索Tom我希望程序打印的第一和最後一個句子,如果我搜索Andy程序應該只打印第二句。

我瘋了,因爲我所做的只是打印TomAndy。 這是我的代碼:

Pattern p =Pattern.compile("Tom\\w+") 
+4

什麼是句子的定義? – anubhava 2014-10-11 06:42:04

+0

您的模式與單詞「Tom」匹配,後跟一個或多個單詞字符。你的例句中沒有這些句子,它只有「湯姆」,後面跟着非單詞字符。你可能不喜歡這樣,因爲它涉及閱讀,但請閱讀http://www.regular-expressions.info,瞭解如何使用正則表達式。這可能是你生命中的幾個小時,將會永遠得到回報。 – 2014-10-11 06:42:25

回答

0

如果我理解你的問題吧,你想匹配2句爲Tom和1 Andy。你想這樣做:

String line = "hi Tom how are you.hey Andy its nice to see you.where is your wife Tom."; 

String pattern = "[\\w\\s]*Tom[\\w\\s]*[\\.]?"; 

Pattern r = Pattern.compile(pattern); 
Matcher m = r.matcher(line); 

while (m.find()) { 
    System.out.println("Find: " + m.group(0)); 
} 

輸出:

Find: hi Tom how are you. 
Find: where is your wife Tom. 
0

如果你是一個初學者,那麼試試下面的代碼。您可以通過在一次迭代中檢查多個鍵/人名來提高效率。

public class Tommy { 

    public static void main(String[] args) { 

     String junk = "hi Tom how are you.hey Andy its nice to see you.where is your wife Tom."; 
     System.out.println(junk); 
     String [] rez = extractor(junk, "Tom"); 
     printArray(rez); 

    } 

    public static String[] extractor(String text, String key) { 
     String[] parts = text.split("\\."); 
     String[] rez = new String[parts.length];// Use an arraylist ? 

     for (int i = 0; i < parts.length; i++) { 
      if (parts[i].contains(key)) { 
       rez[i] = parts[i]; 
      } 
     } 

     return rez; 
    } 

    public static void printArray(String[] ar) { 

     for (int i = 0; i < ar.length; i++) { 
      if (ar[i] != null) { 
       System.out.println(ar[i]); 
      } 
     } 

    } 

} 
0

假設每個句子"."結束,則:

public List<String> findMatches(String string, String name) { 
    List<String> result = new ArrayList<String>(); 
    Pattern p = Pattern.compile("[\\w\\s]*" + name + "[\\w\\s]*");  
    for (String s : string.split("\\.")) { 
     Matcher m = p.matcher(s); 
     if(p.matcher(s).matches()) 
      result.add(s); 
    } 
    return result; 
} 


String string = "hi Tom how are you. hey Andy its nice to see you. where is your wife Tom."; 
System.out.println(findMatches(string, "Tom"); 
System.out.println(findMatches(string, "Andy");