2015-10-29 40 views
1

我試圖對某些格式錯誤的文本應用正則表達式。一般格式爲:正則表達式捕獲畸形文本中的組

descriptor (one|two|three|four) code

理想的輸入例如:

hello world (one) 0039x

我想捕捉3組:

"hello world", "one", "0039x"

(請注意在缺少括號組(2))

格式錯誤的例子:

hello (world) (two) 0039x 
hello (world) three 0039x 
hello world, four 0039x 
hello (world)*,four 0039x 

descriptor應該保留任何括號和符號(但逗號被忽略),即"hello (world)*"也是有效的。

這裏是我想出了:

([a-z0-9 \*\(\)]*),?\s?\(?(one|two|three|four)\)?\s([a-z0-9]+)

它的工作好,但問題是descriptor趨於貪婪地捕捉開括號。即,從理想的例子:

"hello world (", "one", "0039x"

什麼是更好的正則表達式將與正常情況下的工作,也是畸形的情況?前瞻可能有用,但我不知道如何使用(?:...)並捕獲任何括號,如果它也是descriptor的一部分。

回答

0

假設你想匹配,直到剛剛(one|two|three|four)之前逗號或空格,你可以使用這個表達式:

^(.+?)[\s,]\(?(one|two|three|four)\)?\s([a-z0-9]+)$ 

RegEx Demo

0

這似乎與你的正則表達式唯一的問題是,你有括號可選,而您的好/壞樣品暗示它們是必需的(刪除2 ? s):

([a-z0-9 \*\(\)]*),?\s?\((one|two|three|four)\)\s([a-z0-9]+)