2015-07-04 28 views
0

我一直在試圖捕捉低於複雜的正則表達式捕獲 - 使用Javascript

a1A ^(?\..*+) and a1A ^(?\..*+) g:a1A ^(?\..*+) 

的一部分。但是我不能爲我所試圖達到100%的工作正則表達式。

正則表達式必須在冒號後面跟着一個冒號,也就是冒號前面的字母,然後它必須在第一次匹配後面跟一個冒號和冒號前面的字母直到空格之後捕獲。例如下面這一行:

x:a1A ^(?\..*+) z:a1A ^(?\..*+) g:a1A ^(?\..*+) 

--> captured value must be 'x', 'a1A ^(?\..*+)', 'z', and 'a1A ^(?\..*+) g:a1A ^(?\..*+)' 

另一個例子

x23:a1A ^(?\..*+) z:a1A ^(?\..*+) g:a1A ^(?\..*+) 

--> captured value must be 'x23', 'a1A ^(?\..*+)', 'z' and 'a1A ^(?\..*+) g:a1A ^(?\..*+)' 

,然後在萬一沒有字符串開頭的任何字母和後跟一個冒號,那麼它必須捕獲任何直到空格後緊跟字母或字母和冒號。例如

a1A ^(?\..*+) s:a1A ^(?\..*+) 

--> captured value must be 'a1A ^(?\..*+)', 's' and 'a1A ^(?\..*+) 
+0

你不是故意拆'G'它也部分出現在第三個例子中,這就是爲什麼它可能是一個錯字。假設你的前兩個例子的最後一個捕獲組是'a1A ^(?\ .. * +)''g'和'a1A ^(?\ .. * +)',我會發佈一個答案。 '。 –

+0

@machee對不起,我編輯了我的問題並修正了最後一個例子,它必須捕獲第三個字母:前2個例子中的anychar模式,前2個字母:anychar模式是分隔符。 –

回答

0

我想出的正則表達式是?:([^: ]+):)?([^ ]+ [^ ]+)(?: |$)

(?:([^: ]+):)? // don't capture the colon, capture the part before the colon 
([^ ]+ [^ ]+) // capture the two groups that may or may not be preceded by the colon 
(?: |$)   // end at either a space or the end of the line/string 

這裏是一個小提琴,我測試了它:在第一兩個例子a1A`部分:http://jsfiddle.net/9nbsu84v/