Regex find the contents of the question

Trying to use the regex refind tag to search for the contents in brackets in this example using coldfusion

joe smith < joesmith@domain.com > 

The final text should be

 joesmith@domain.com 

Using this

 <cfset reg = refind( "/(?<=\<).*?(?=\>)/s","Joe < joe@domain.com >") /> 

Bad luck. Any suggestions?

Perhaps a syntax problem, it works in the online regular expression test that I use.

+6
coldfusion regex
source share
3 answers

You cannot use lookbehind with the CF regex engine (uses Apache Jakarta ORO ).

However, you can use Java regex , although it supports them, and I created a CFC wrapper that makes it even easier. Available from: http://www.hybridchill.com/projects/jre-utils.html

(Update: The CFC wrapper mentioned above has evolved into a complete project. See cfregex.net for details.)

In addition, the material /.../s is not required / matters here.

So, from your example, but with improved regex:

 <cfset jrex = createObject('component','jre-utils').init()/> <cfset reg = jrex.match( "(?<=<)[^<>]+(?=>)" , "Joe < joe@domain.com >" ) /> 


A quick note, since I updated this regex several times; I hope this is at its best ...

 (?<=<) # 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 a `>` but don't capture it. 
+9
source share

I have never been happy with regex features in CF. Therefore, I wrote my own:

 <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 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> 

As applied to your problem, here is my example:

 <cfset origString = "joe smith < joesmith@domain.com >" /> <cfset regex = "<([^>]+)>" /> <cfset matches = reFindNoSuck(regex, origString) /> 

Dropping the variable "matches" indicates that it is an array with two elements. The first will be < joesmith@domain.com > (because it matches the entire regular expression), and the second will be joesmith@domain.com (since it matches the first group defined in the regular expression, all subsequent groups will also be captured and included in the array).

0
source share
 /\<([^>]+)\>$/ 

something like that, did not check, although one of you;)

-one
source share

All Articles