2009-06-18 12 views
3

私はしばらくの間これをしてきましたが、うまくいかないようです。ここに私がやろうとしていることがあります。 3つの単語word1、word2、word3が与えられたら、それらの順にそれらにマッチする正規表現を作成したいと思いますが、それらの間に一連の潜在的な単語があります(改行を除く)。例えばRegEx - 単語のセットを一致させる

、私が持っていた場合には、以下:

word1 = what 
word2 = the 
word3 = hell 

は、私はシングルマッチで、次の文字列にマッチしたい:私は次の操作を行うことができると思った

"what the hell" 
"what in the hell" 
"what the effing hell" 
"what in the 9 doors of hell" 

(可能

regex = "\bword1(\b\w+\b){0,5}word2(\b\w+\b){0,5}word3\b" 

アラート、いいえ、それは機能しません。単語間のmからnまでの単語の距離を指定する方法があることが重要です(mは常に< nです)。 (Rubyで)私にとって

答えて

1
$ cat try 
#! /usr/bin/perl 

use warnings; 
use strict; 

my @strings = (
    "what the hell", 
    "what in the hell", 
    "what the effing hell", 
    "what in the 9 doors of hell", 
    "hello", 
    "what the", 
    " what the hell", 
    "what the hell ", 
); 

for (@strings) { 
    print "$_: ", /^what(\s+\w+){0,5}\s+the(\s+\w+){0,5}\s+hell$/ 
        ? "match\n" 
        : "no match\n"; 
} 

$ ./try 
what the hell: match 
what in the hell: match 
what the effing hell: match 
what in the 9 doors of hell: match 
hello: no match 
what the: no match 
what the hell: no match 
what the hell : no match 
+0

これは今のところ最もエレガントで、広告されたとおりに動作しますが、サブマッチがあります。あなたは私に言います、それについて気にしますか?私は、文字列全体が先頭の単語1、末尾の単語2、途中の単語3(「中間のどこか」は単語の距離の問題です)と一致していることが最も大事です。 –

+0

これは、パターンにアンカーを追加するのと同じくらい簡単です。改訂されました! –

+0

サブマッチは気にしないでください。あなたは常に一致する文字列全体を得ることができます。以下で述べるpythonでは、matchobj.group(0)でこれを行います。 サブグループに全く反対の場合は、すべての括弧を(\ s + \ w +)から(?:\ s + \ w +)に切り替えて、サブグループを取得しないようにしてください。 – Clint

2

"\bwhat(\s*\b\w*\b\s*){0,5}the(\s*\b\w*\b\s*){0,5}hell"作品のClojureでの私のために

list = ["what the hell", "what in the hell", "what the effing hell", 
    "what in the 9 doors of hell", "no match here hell", "what match here hell"] 

list.map{|i| /\bwhat(\s*\b\w*\b\s*){0,5}the(\s*\b\w*\b\s*){0,5}hell/.match(i) } 
=> [#<MatchData:0x12c4d1c>, #<MatchData:0x12c4d08>, #<MatchData:0x12c4cf4>, 
    #<MatchData:0x12c4ce0>, nil, nil] 
+0

これは、フレーズ全体と、group(1)の ''の結果を返すことの両方に一致しています。 同じ結果で(\ s * \ w * \ s *){0,5}も試しました。これは私が自分で持っているよりもはるかに遠いです!助言がありますか?私はPythonでこれをやっています。 –

0

作品:ベン・ヒューズのパターンどおり

(def phrases ["what the hell" "what in the hell" "what the effing hell" 
       "what in the 9 doors of hell"]) 

(def regexp #"\bwhat(\s*\b\w*\b\s*){0,5}the(\s*\b\w*\b\s*){0,5}hell") 

(defn valid? [] 
    (every? identity (map #(re-matches regexp %) phrases))) 

(valid?) ; <-- true 

関連する問題