2010-04-02 29 views
3

如何編寫正則表達式以隨機順序匹配多個單詞?使用正則表達式搜索匹配隨機排列的多個單詞的字符串

例如,假設下面幾行:

Dave Imma Car Pom Dive 
Dive Dome Dare 
Imma Car Ryan 
Pyro Dave Imma Dive 
Lunar Happy Dave 

我想搜索的字符串的一個匹配的「戴維」「伊馬」和「潛水」,預計第1和第4行。這可能嗎?

+0

這對於正則表達式來說不是一件好事。正則表達式用於模式匹配,但您的任務包含難以在模式中表達的邏輯。另外,你還沒有指定什麼語言。 – 2010-04-04 23:08:37

回答

0
if ((matches "/(Dave|Imma|Dive) (Dave|Imma|Dive) (Dave|Imma|Dive)/") 
&& (contains("Dave")) && (contains("Imma")) && (contains("Dive"))) 
{ 
    // this will work in 90% of cases. 
} 

儘管如此,我認爲不可能做到這一點。抱歉。

0
String[] lines = fullData.split("\n"); 
String[] names = {"Dave", "Imma", "Dive"}; 
ArrayList matches = new ArrayList(); 

for(int i=0; i<lines.size(); i++){ 
    for(String name : names){ 
     // If any of the names in the list isn't found 
     // then this line isn't a match 
     if(!lines[i].contains(name)){ 
      continue; 
     } 
    } 
    // If we made it this far, all of the names were found 
    matches.add(i); 
} 
// matches now contains {1, 4} 

如果你不需要知道比賽是,它可以簡化爲:

String[] lines = fullData.split("\n"); 
String[] names = {"Dave", "Imma", "Dive"}; 

for(String line : lines){ 
    for(String name : names){ 
     // If any of the names in the list isn't found 
     // then this line isn't a match 
     if(!line.contains(name)){ 
      continue; 
     } 
    } 
    // If we made it this far, all of the names were found 

    // Do something 
} 
3

如果你堅持使用正則表達式這樣做,你可以使用前瞻:

s.matches("(?=.*Dave)(?=.*Imma)(?=.*Dive).*") 

儘管如此,Regex並不是最有效的方法。

0

以下幾行匹配?

Dave Imma Dave 
Dave Imma Dive Imma 

我猜第一個不應該是因爲它不包含所有三個名字,但重複的好嗎?如果不是的話,這個正則表達式的訣竅是:

^(?:\b(?:(?!(?:Dave|Imma|Dive)\b)\w+[ \t]+)*(?:Dave()|Imma()|Dive())[ \t]*){3}$\1\2\3 

我使用「trick」這個詞。 :)這證明了一個正則表達式可以完成這項工作,但我不希望在任何嚴重的應用程序中看到這個正則表達式。爲此目的寫一個方法會更好。

(順便說一句,如果允許的,只是刪除$重複。)

編輯:另一個問題是:應該在名稱中只有在完整的單詞形式是否匹配?換句話說,如果這些線匹配?

DaveCar PomDive Imma 
DaveImmaDive 

到目前爲止,着重加強了獨特和完整的單詞只有對方的回答是冠斑的,它不能匹配多餘的話行,像這樣:

Dave Imma Car Pom Dive 
Pyro Dave Imma Dive 
2
在* nix中

,你可以如果爲了

awk '/Dave.*Imma.*Dive/' file 

如果不是爲了用awk

awk '/Dave/ && /Imma/ && /Dive/' file 
+0

你確定這有效嗎? – 2013-03-15 20:42:29

相關問題