2011-11-18 81 views
0

說我有一個元素在我的HTML頁面,如下所示:正則表達式來捕獲此模式中的單引號字符串...?

<span class="special caption['This &lt;em&gt;expression&lt;/em&gt; describes this element.']">ABC</span> 

我想使用jQuery來提取類屬性這個「標題」。我知道如何隔離

caption['This &lt;em&gt;expression&lt;/em&gt; describes this element.'] 

但什麼正則表達式可以讓我解壓

這<EM>表達</EM >描述該元素。

如果我可以在撇號中包含轉義序列,例如,

caption['This &lt;em style=\'color: #FF0000;\'&gt;expression&lt;/em&gt; describes this element.'] 

,並得到

這< EM風格= 'COLOR:#FF0000;' >表達式</em >描述了這個'元素'。

感謝您的幫助。我真的在正則表達式中受到挑戰......

+0

我猜你並不是說在你的最後一個塊的'element'之前有'''字符在那裏引用? –

+0

噢,是的,對不起,我修改了我的示例以使用標記屬性而不是單引號。 –

回答

1

你也許不應該把這個信息到類屬性(見locrizak的答案),但如果您因某種原因絕對需要,請繼續閱讀。

我不認爲你需要一個正則表達式。如果你已經知道如何得到它歸結爲這樣:

caption['This &lt;em&gt;expression&lt;/em&gt; describes this element.'] 

...那麼所有你需要做的是採取該字符串和串吧,就像這樣:

var s = "caption['This &lt;em&gt;expression&lt;/em&gt; describes this element.']"; 
s = s.substring(9, s.length - 2); 
+0

哇。杜時刻。謝謝......我不知道爲什麼我沒有想到這一點。 –

2

Class完全是這樣做的錯誤地方。

這是正確的做法:

<span data-caption="This <em style=\'color: #FF0000;\'>expression</em> describes this element."></span>

,然後你可以通過jQuery的訪問:

$('span').attr('data-caption')
+0

當然,OP可能無法控制HTML被解析,從而提示使用jQuery ......但是我知道什麼? –

+0

$('span')。data('caption')也可以。 –

+0

兩者都是正確的.. – locrizak

1

我不是最有經驗與jQuery的功能,但你可以試試這個表達式:

/class=".*?caption\['((?:\\'|[^'])*)'/m 

我知道它是能夠找到任何classcaption類屬性的,你有ABO格式來自任何字符串並匹配單引號(')的內容,允許單一轉義的單引號(\')。

有了這個HTML:

<span class="special caption['This &lt;em&gt;expression&lt;/em&gt; describes this element.']">ABC</span> 
<span class="special caption['This &lt;em style=\'color: #FF0000;\'&gt;expression&lt;/em&gt; describes this element.']">ABC</span> 

發現兩個匹配(在拍攝第1組):

This &lt;em&gt;expression&lt;/em&gt; describes this element. 
This &lt;em style=\'color: #FF0000;\'&gt;expression&lt;/em&gt; describes this element. 

我希望這可以幫助你!

JavaScript沒有外觀,或者我會提供一個只匹配你想要的文本的解決方案 - 可以用兩個表達式完成,如果你只能得到整個匹配並且不能訪問第一個比賽組。

相關問題