我試圖對某些格式錯誤的文本應用正則表達式。一般格式爲:正則表達式捕獲畸形文本中的組
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
的一部分。