2016-09-27 10 views
2

検索フィールドで使用する正規表現を次のように作成しました。問題は、それが常に正しく一致していないことである正規表現を最大2語と一致させる正規表現

/^ 
    .*?     # match anything before, as few times as possible 
    (
     (?: 
      [^\s]+\s* # anything followed by whitespace 
     ){1,2}   # match once or twice 
     \s*?   # match whitespaces that may be left behind, just in case 
     [^\s]*?   # match the beginning of the word, if exists 
    )? 
    (foo|bar)   # search term(s) 
    ([^\s]*\s*.*)  # whatever is after, with whitespace, if it is the end of the word 
$/xi 


目標は後に、その後、2ワードまで一致する文字(複数可)およびすべてと完全な単語を、それを使用することです。 「A」を検索
いくつかの例、:

Fantastic drinks and amazing cakes 

Expected match: 
$1 = F 
$2 = a 
$3 = ntastic drinks and amazing cakes 

Result: 
$1 = Fantastic drinks (space) 
$2 = a 
$3 = nd amazing cakes 

----------------------------------------- 

Drinks and party! 

Expected match: 
$1 = Drinks (space) 
$2 = a 
$3 = nd party! 

Result: 
$1 = Drinks and p 
$2 = a 
$3 = rty! 

------------------------------------------ 

Drinks will be served at the caffetary in 5 minutes 

Expected match: 
$1 = be served (space) 
$2 = a 
$3 = t the caffetary in 5 minutes 

Result (matches correctly): 
$1 = be served (space) 
$2 = a 
$3 = t the caffetary in 5 minutes 

あなたは付属のユニットテストでhttps://regex101.com/r/cI7gZ3/1上でそれを試すことができます。

これがうまくいかない方法は、私が説明できるものではありません。しかし、私の推測では、これは、の前に、1-238語の一致を好むものであるということです。の検索語です。

ここで間違っていると思われますか?それがこれらの問題を引き起こしていると思いますか?

+0

参照してください?キャプチャされた部品はどのようにすべきか? – revo

+0

2番目のキャプチャグループにあるもの(私は 'search term'と呼ばれます)が私の例で使用された" a "であれば、1番目のグループに' Ffff'を、3番目に 'ntastic'を格納する必要があります。 –

+0

私はあなたが答えを受け入れるのを見るが、質問:あなたは文字とスペースだけを持っていますか、または他の文字も入力文字列に入れることができますか? – revo

答えて

1

私は

(?: 
    \S+?\s* # anything followed by whitespace 
){1,2}? 

\S+{1,2}の怠惰なバージョンを使用することをお勧めして​​一部を除去。

は何 `Ffffantastic`についてupdated regex demo

^ 
    .*? # match anything before, as few times as possible 
    (
    (?: 
     \S*?\s* # anything followed by whitespace 
    ){1,2}? 
    \s* # just in case there's whitespace 
)? 
    (a) # search term(s) 
    (\S*\s*.*) # whatever is after, without whitespace if it is the end of the word 
$ 
+0

'Fantastic drink and amazing cakes'では、' Fant 'の代わりに 'Fant'とマッチします。 –

+0

更新しました。再確認してください。 –

+1

これで完璧に動作しています!ありがとうございました! –

関連する問題