試圖將第三個項目匹配此列表:的Perl風格的正則表達式的匹配列表的第n項
/text word1, word2, some_other_word, word_4
我使用這個perl的風格正則表達式無濟於事嘗試:
([^, ]*,){$m}([^, ]*),
我想只匹配第三個單詞,沒有任何之前或之後,沒有逗號或空格。我需要它是一個正則表達式,這不是在一個程序中,而是一個字文件的UltraEdit。
我可以用它來搭配some_other_word(或任何第三列表。)
試圖將第三個項目匹配此列表:的Perl風格的正則表達式的匹配列表的第n項
/text word1, word2, some_other_word, word_4
我使用這個perl的風格正則表達式無濟於事嘗試:
([^, ]*,){$m}([^, ]*),
我想只匹配第三個單詞,沒有任何之前或之後,沒有逗號或空格。我需要它是一個正則表達式,這不是在一個程序中,而是一個字文件的UltraEdit。
我可以用它來搭配some_other_word(或任何第三列表。)
基於由社區成員的一些輸入我提出了以下變化做出更清晰的正則表達式模式的邏輯。
/^(?:(?:.(?<!,))+,){2}\s*(\w+).*/x
說明
/^ # 1.- Match start of line.
(?:(?:.(?<!,))+ # 2.- Match but don't capture a secuence of character not containing a comma ...
,) # 3.- followed by a comma
{2} # 4.- (exactly two times)
\s* # 5.- Match any optional space
(\w+) # 6.- Match and capture a secuence of the characters represented by \w a leat one character long.
.* # 7.- Match anything after that if neccesary.
/x
這是一個先前建議。此正則表達式的
/(?:\w+,?\s*){3}(\w+)/
這不可能一次只返回一個匹配項,因爲您的字符串有多個出現,並且Regular Expression
沒有選擇性返回選項! 所以你可以做任何你想從返回的數組。
,\s?([^,]+)
See it in action,第二匹配組是你所需要的。
我不明白你爲什麼做逗號可選。它適用於提供的示例,但使正則表達式非常脆弱。它會失敗,如'word1,word2,some_other_word,word_4'或'文字word1,文字word2,some_other_word,word_4' – Birei
它會在給定的例子中觀看'word_4',但需要'some_other_word'。 – Toto
@ M42:我認爲它有效,但不是他期望的方式。第一次出現匹配'text',第二次匹配'word1',第三次匹配'word2,'(注意每個單詞之後的空格)。 – Birei