Regular Expression Question

Ken Ray kray at sonsothunder.com
Tue Jul 10 11:20:10 EDT 2007


On Tue, 10 Jul 2007 09:55:18 -0500, Len Morgan wrote:

> I need to find the last matching character offset of a string withing 
> another string.  The offset function only gives me the first one.  Is 
> there a function I'm missing (like "offset from end of string") or a 
> one or two liner I can use?
> 
> Example:
> 
> approved_by_code - I'm looking for the offset to the second "_" 
> character so the result should be 12 in this example.  It is also 
> possible that there will only be one "_" character in which case, 
> that is the offset I want.

Well, here you go - regex is normally "greedy" (meaning it find the 
last match in a string), but Rev's is "non-greedy", so it finds the 
first match. So if you did this:

on mouseUp
  if matchChunk("approved_by_code","(_)",tStart,tEnd) then
    put tStart,tEnd
  else
    put "not found"
  end if
end mouseUp

You'd get "9,9" in the message box - the first hit. So you need to 
reverse the "greediness" of the match using the (?U) directive. This 
one works to find the last occurrence:

on mouseUp
  if matchChunk("(?U)approved_by_code","(_)",tStart,tEnd) then
    put tStart,tEnd
  else
    put "not found"
  end if
end mouseUp

HTH,

Ken Ray
Sons of Thunder Software, Inc.
Email: kray at sonsothunder.com
Web Site: http://www.sonsothunder.com/



More information about the use-livecode mailing list