2013-01-16 40 views
-1

下面的文本是使用正則表達式從巨大文本中過濾出來的,我必須找到沒有porc和pig的狗和貓的句子。如何選擇2個單詞之間有3個或更多字符的單詞

What, a Dog, a Rat, a Mouse, a Cat to scratch a man to 
Where Iuliet liues, and euery Cat and Dog, 
Which first (perchance) shee'l proue on Cats and Dogs, 
glass, and from setting up memorials of departed cats and dogs. 
Thinking,' etc., 1873, p. 82.), "A dog frames a general concept of cats or 
dog, who never passed a cat who lay sick in a basket, and was a great 

要了解什麼是上面我用正則表達式:

^(?!.\*porc.\*)(?!.\*pig.\*)(?=.\*\bdog\b.\*)(?=.\*\bcat\b.\*).\* 

現在,我必須找到狗和貓之間的話具有3個字符等等。

我想:

^(?!.\*porc.\*)(?!.\*pig.\*)(?=.\*\bdog\b.\*)(?=.\*\bcat\b.\*)dog(?:\s?\w{3,})+cat 

它不工作。

任何人都有如何解決它的想法?

+0

在給出的示例文本中,您想要檢索什麼?我對此不太清楚。如果您可以顯示一些示例輸出... –

+0

根據我的經驗,當涉及複雜的邏輯時(如在其他單詞之間搜索單詞),我可以說正則表達式不是一個好工具。我建議使用不同的工具來提取所需的子字符串,然後將簡單的搜索正則表達式應用於每個子字符串。 – Anton

+0

您可以使用'indexOf'來檢查而不是在正則表達式中查找。如果字符串有多個「狗」和「貓」,你的預期輸出是什麼? – nhahtdh

回答

0

讓我先說這個,說我對Java的熟悉程度不是最好的(我在任何語言聯繫被聲明之前回答了這個問題)。說了這些,我認爲你的問題需要兩個正則表達式,因爲(據我所知)Java不支持重複組的捕獲。爲了說明您需要什麼,請考慮您正在尋找的整體模式。我已經包括從你的第一個例子比賽(「什麼,狗,大鼠,小鼠,貓搔男人」)在雙星號:

(?P<animal> // Names the following group "animal" for later reference 
    \b(dog|cat) // **Dog** 
) // Ends "animal" group 
[s]?\b\W+ // **, ** 
(?!\bporc\b\W+|\bpig\b\W+|(?P=animal)\W+) // Not followed by porc, pig, or characters that match group "animal" (either 'cat' or 'dog') 
.*? // Characters up to first word of three characters or more **a ** 
(
    (
     (
      (
       (\b\w{3,}\b) // The (repeated) group you are after (**Rat**/**Mouse**) 
      \W+)+ // (**, **/**, **) 
     ) 
      (?:\b\w{0,2}\b\W+)* // A group that will not be available after the search (**a **/**a **) 
     )+ 
    ) 
(?! // Not followed by 
    (?P=animal) // the characters that matched group "animal" above (either dog or cat) 
)\b 
(cat|dog)[s]{0,1}\b // Followed by dog or cat, whichever was not the "animal" group above **Cat** 

由於Java只捕獲最後的重複的組(與.NET和其他允許捕獲重複組的語言不同),您很可能需要分兩步進行查詢。首先,您需要查找貓或狗與狗或貓之間的所有字符串(只要第一組不像第二組)。您可以使用正則表達式像下面找到這些字符串:

(?P<animal>\b(dog|cat))[s]{0,1}\b\W+(?!\bporc\b\W+|\bpig\b\W+|(?P=animal)\W+)(.*?)(?!(?P=animal))\b(cat|dog)[s]{0,1}\b 

你會想找到3組,這是(*?)。

後,你在每個相關的字符串/句子識別組3,你會想使用類似以下(基於this post):

Pattern regex = Pattern.compile("\b\w{3,}\b"); 
Matcher regexMatcher = regex.matcher(subjectString); 
while (regexMatcher.find()) { 
    // matched text: regexMatcher.group() 
    // match start: regexMatcher.start() 
    // match end: regexMatcher.end() 
} 

不幸的是,你不能只使用一個(合理)的正則表達式捕捉您在Java中需要的所有單詞,因爲您不知道狗和貓之間會出現多少個三個字母的單詞。我希望這有幫助。

+0

不知道我已經瞭解....我正在使用java – user1985137

+0

我剛更新了答案。鑑於您使用的是Java,我希望它更清楚。 –

相關問題