2013-04-13 25 views
1

特定單詞(JAVA)我有一個單詞列表一句:正則表達式查找包含從段落

我想在Java中想出一個正則表達式來從包含任何一個單詞(不區分大小寫)的長段落中提取句子。這句話結束於.?! 任何人都可以幫忙嗎?謝謝!

+1

所以你的正則表達式的問題是什麼?還有句子是否包含像狗一樣的東西,可以接受嗎? – Pshemo

+0

所以輸入字符串是一個長段落,可能有幾個句子需要匹配? –

回答

0

嘗試這個表達式

str.matches("(?i)(^|\\s+)(dog|cat|leopard)(\\s+|[.?!]$)"); 

(我)是一種特殊結構,這意味着不區分大小寫

1

這應該這樣做。你只需要在中間填充你想要的單詞。例如:

你好我有狗,我喜歡做事嗎?不要以我的弱點爲善。我的樹皮比一個高音的叮咬更好!所以把我帶到另一隻動物身上。像一隻貓。

比賽:

你好我是一隻狗,我喜歡做的事情? 我的樹皮比一個超音波的叮咬更好! 就像一隻貓。並做到這一點(?我)忽略大小寫。我沒有把它放進去,因爲我沒有真正記得語法,但有人寫了它

"(?=.*?\\.)[^ .?!][^.?!]*?(dog|cat|leapord).*?[.?!]" 
0

(貓)。(\。| \?| \!)$,你應該使用java.util.regex.Pattern的CASE_INSENSITIVE選項。

3

以下假定句子以大寫字母開頭,除句尾外,句子中沒有.,!?

String str = "Hello. It's a leopard I think. How are you? It's just a dog or a cat. Are you sure?"; 
Pattern p = Pattern.compile("[A-Z](?i)[^.?!]*?\\b(dog|cat|leopard)\\b[^.?!]*[.?!]"); 
Matcher m = p.matcher(str); 

while (m.find()) { 
    System.out.println(m.group()); 
} 
// It's a leopard I think. 
// It's just a dog or a cat. 
3

假設

  • 句子必須在兩者之間有大寫字母沒有行結束開始[。?!]。
  • 關鍵字匹配不區分大小寫。但是,子字符串匹配無效。
  • 關鍵字可能出現在句子的任何地方(開始,結束或中間)。
  • 支持報價和非正式雙標點符號。如果不需要,請使用第二個正則表達式。

public class SentenceFinder { 

    public static void main(String[] args) { 
     String paragraph = "I have a list of words to match: dog, cat, leopard. But blackdog or catwoman shouldn't match. Dog may bark at the start! Is that meow at the end my cat? Some bonus sentence matches shouldn't hurt. My dog gets jumpy at times and behaves super excited!! My cat sees my goofy dog and thinks WTF?! Leopard likes to quote, \"I'm telling you these Lions suck bro!\" Sometimes the dog asks too, \"Cat got your tongue?!\""; 
     Pattern p = Pattern.compile("([A-Z][^.?!]*?)?(?<!\\w)(?i)(dog|cat|leopard)(?!\\w)[^.?!]*?[.?!]{1,2}\"?"); 
     Matcher m = p.matcher(paragraph); 
     while (m.find()) { 
      System.out.println(m.group()); 
     } 
    } 
    /* Output: 
     I have a list of words to match: dog, cat, leopard. 
     Dog may bark at the start! 
     Is that meow at the end my cat? 
     My dog gets jumpy at times and behaves super excited!! 
     My cat sees my goofy dog and thinks WTF?! 
     Leopard likes to quote, "I'm telling you these Lions suck bro!" 
     Sometimes the dog asks too, "Cat got your tongue?!" 
    */ 
} 


簡化正則表達式,如果「行情?「(或非正式的標點符號)不要求:
"([A-Z][^.?!]*?)?(?<!\\w)(?i)(dog|cat|leopard)(?!\\w)[^.?!]*?[.?!]"

要獲取這些句子,以及不以大寫字母開頭(如果輸入可能有這樣的錯別字):
"(?i)([a-z][^.?!]*?)?(?<!\\w)(dog|cat|leopard)(?!\\w)[^.?!]*?[.?!]"

+0

我認爲這很明顯,但我仍然會提到引號「」不是(最後兩個)正則表達式的一部分,它們只是讓一個人複製粘貼表達式作爲String爭論輕鬆地訪問'Pattern.compile()'。 –

相關問題