2011-03-16 28 views
0

如何匹配此轉義的html字符串的id?字符串的一部分使用id = \啓動「與\結束」在這個例子中,我需要art_images_attributes_0_attachementRuby匹配轉義的html字符串的一部分

"<div class=\"input string optional\"><label class=\"string optional\" for=\"art_images_attributes_0_attachement\"> Attachement</label><input class=\"string optional\" id=\"art_images_attributes_0_attachement\" maxlength=\"255\" name=\"art[images_attributes][0][attachement]\" size=\"50\" type=\"text\" /></div>" 
=> "<div class=\"input string optional\"><label class=\"string optional\" for=\"art_images_attributes_0_attachement\"> Attachement</label><input class=\"string optional\" id=\"art_images_attributes_0_attachement\" maxlength=\"255\" name=\"art[images_attributes][0][attachement]\" size=\"50\" type=\"text\" /></div>" 

最好的問候。 阿斯布喬恩·莫雷爾

回答

1

下面的正則表達式將捕捉你想要的outputp:

/id="([^"]*)"/ 

並有Rubular:http://www.rubular.com/r/dtXqK2GBPe

注意,有實際上並不是引號前的\字符,在Ruby中字符串內容"id=\"test\""id="test"\只是爲了逃避任何應該包含的"

因此,它也將與id值內轉義引號的工作,你可以使用這個:

/id="([^"\\]*(?:\\.[^"\\]*)*)"/ 

http://www.rubular.com/r/b66eWno8Ce

+0

謝謝,這正是我正在尋找的。 string.match(/ ID = 「([^」] *)「/)[1] – atmorell 2011-03-17 08:29:31

0

正則表達式明智,這將做到這一點:

id=\\\"(.+?)\\\" 
+0

尼克,你的榜樣返回nil – atmorell 2011-03-17 08:27:44

+0

正如安德魯的回答解釋。我的(天真的)答案是基於這樣的想法,即我需要完全匹配你的問題 - 我不理解這個問題被忽略。 – Nick 2011-03-17 08:39:35