2010-06-15 16 views
6

嘗試使用正則表達式refind標籤使用ColdFusion正則表達式查找內容問題

joe smith <[email protected]> 

找到在這個例子中,括號內的內容所得到的文本應該是

[email protected] 

使用這種

<cfset reg = refind(
"/(?<=\<).*?(?=\>)/s","Joe <[email protected]>") /> 

沒有任何運氣。有什麼建議麼?

也許是一個語法問題,它適用於我使用的在線正則表達式測試程序。

+0

你如何告訴我們你曾經嘗試過,但沒有工作?從那裏開始更容易... – jhwist 2010-06-15 15:07:40

回答

9

你不能在CF的正則表達式引擎中使用lookbehind(使用Apache Jakarta ORO)。

但是,您可以使用Java's regex,但它支持它們,並且我創建了一個包裝CFC,使其更加容易。可從以下 http://www.hybridchill.com/projects/jre-utils.html

(更新:。上面提到的包裝CFC已演變成一個完整的項目見cfregex.net瞭解詳細信息)

此外,/.../s東西ISN」這裏要求/相關。

所以,從你的榜樣,但是具有更高的正則表達式:

<cfset jrex = createObject('component','jre-utils').init()/> 

<cfset reg = jrex.match("(?<=<)[^<>]+(?=>)" , "Joe <[email protected]>") /> 


快速注意,因爲我已經更新了該正則表達式幾次;希望現在是最好的...

(?<=<) # positive lookbehind - start matching at `<` but don't capture it. 
[^<>]+ # any char except `<` or `>`, the `+` meaning one-or-more greedy. 
(?=>) # positive lookahead - only succeed if there's a `>` but don't capture it. 
+0

你是一個天才彼得。這效果很好..感謝您的幫助 – jeff 2010-06-15 18:07:59

-1
/\<([^>]+)\>$/ 

類似的東西,沒雖然測試,一個是你的;)

0

我從來沒有高興的正則表達式匹配CF.功能因此,我寫我自己:

<cfscript> 
    function reFindNoSuck(string pattern, string data, numeric startPos = 1){ 
     var sucky = refindNoCase(pattern, data, startPos, true); 
     var i = 0; 
     var awesome = []; 

     if (not isArray(sucky.len) or arrayLen(sucky.len) eq 0){return [];} //handle no match at all 
     for(i=1; i<= arrayLen(sucky.len); i++){ 
      //if there's a match with pos 0 & length 0, that means the mime type was not specified 
      if (sucky.len[i] gt 0 && sucky.pos[i] gt 0){ 
       //don't include the group that matches the entire pattern 
       var matchBody = mid(data, sucky.pos[i], sucky.len[i]); 
       if (matchBody neq arguments.data){ 
        arrayAppend(awesome, matchBody); 
       } 
      } 
     } 
     return awesome; 
    } 
</cfscript> 

適用於您的問題,這是我的例子:

<cfset origString = "joe smith <[email protected]>" /> 
<cfset regex = "<([^>]+)>" /> 
<cfset matches = reFindNoSuck(regex, origString) /> 

傾銷的「匹配」變量表明,它是與2項的數組。第一個將是<[email protected]>(因爲它匹配整個正則表達式),第二個將是[email protected](因爲它匹配正則表達式中定義的第一個組 - 所有後續組也將被捕獲幷包含在數組中)。

+1

感謝Adam,我能夠使用Peter開發的包裝紙,但也感謝您的兩分錢。 – jeff 2010-06-15 18:08:59