Search / replace

Igor de Oliveira Couto igor at
Sat Feb 20 04:28:19 EST 2010

This sounded like a fun puzzle to solve:

On 20/02/2010, at 7:17 PM, J. Landman Gay wrote:

> Glen Bojsza wrote:
>> Sorry to bother everyone but either I'm tired or brain dead.
>> I have a field which has hundreds of lines.
>> For all [ in the field I need to check to see if the character to it's
>> immediate left is a number.
>> If it is a number then the [ is to be converted into an _.
>> If it is not a number then the [ is to be removed (no substitution or
>> spaces).
>> I need to be able to cycle through the entire field which each line may
>> contain several [.
>> Any thoughts would be appreciated as I have tried using a combination of
>> find characters and foundchunk on the field without success.
> This sounds like a perfect job for the replacetext command; regular expressions are ideal for this kind of problem. You won't need any loops, though you may need to run it twice, once to get all the brackets followed by numbers, and a second time to remove the single brackets. If Alex or Ken or someone else doesn't step in first, I'll see if I can get the regex worked up for you tomorrow. Maybe someone even knows how to test for both situations and replacements in the same expression. I know there's a way to do that but I'm not sure how.
> At any rate, once you get the right regex figured out, it's a one-liner to do what you want.

I tried using replaceText(), but the problem is that it replaces the *entire* text which is 'recognised' by the regex. That would cause problems here. For instance, pinpointing all the "[" characters that are not preceded by a number is easy via regex - the regex is "[^0-9]\[". But the problem is that the 'replaceText' command will identify and replace *everything* in my expression, not just part of it. So, if in this case I ask it to:

replaceText( field "sourceField", "[^0-9]\[", empty)

... it not only deletes the '[', but also the number preceding it.

I came across problems with matchChunk, too, but for a different reason. I wanted to use it in a loop, so I could delete the required parts of each match. Unfortunately, even though it was returning 'true' to my regex - it *was* finding matches - it refused to populate my 'positionvars', so it was useless. 

I ended up writing a simple repeat loop, which seems to have done the trick:

repeat with x = number of chars in field "sourceField" down to 1
      if char x of field "sourceField" is not "[" then next repeat
      if char (x-1) of field "sourceField" is a number then put "_" into char x of field "sourceField"
      else put empty into char x of field "sourceField"
 end repeat

I hope this helps!

Igor de Oliveira Couto
Sydney, Australia

More information about the Use-livecode mailing list