RegEx - соответствие набора слов - PullRequest
3 голосов
/ 18 июня 2009

Я был на этом некоторое время и, кажется, не могу решить это. Вот что я пытаюсь сделать. Учитывая три слова word1, word2 и word3, я хотел бы создать регулярное выражение, которое будет сопоставлять их в этом порядке, но с набором потенциальных слов между ними (кроме новой строки).

Например, если бы у меня было следующее:

word1 = what
word2 = the
word3 = hell

Я бы хотел сопоставить следующие строки с одним совпадением:

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

Я думал, что мог бы сделать следующее (допуская, что между каждой переменной слова существует от 0 до 5 слов):

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

Увы, нет, это не работает. Важно, чтобы у меня был способ указать расстояние между словами от m до n (где m всегда

Ответы [ 3 ]

2 голосов
/ 18 июня 2009

"\bwhat(\s*\b\w*\b\s*){0,5}the(\s*\b\w*\b\s*){0,5}hell" у меня работает (в рубине)

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]
1 голос
/ 18 июня 2009
$ 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 голосов
/ 18 июня 2009

У меня работает в ближайшем будущем:

(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

по схеме Бена Хьюза.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...