regEx to remove spaces ?

Dar Scott dsc at swcp.com
Sat May 20 00:55:51 EDT 2006


On May 17, 2006, at 3:45 AM, jbv wrote:

> Is it possible to use regEx to remove spaces before and
> after quotes, and, if yes, how ?
>
> Example :
>     my " beautiful " laundrette
> becomes
>     my "beautiful" laundrette

(?x)
(?<=")  \ +  (?= [^"]* "  (?>(?:[^"]*"){2})* [^"]* \z)
|
         \ +  (?= "        (?>(?:[^"]*"){2})* [^"]* \z)


on mouseUp
   put replaceText(field "In",field "regex","") into field "Out"
end mouseUp

This is slow for long strings.  The regex experts might have some  
ideas on how to speed that up.  For every match it has to check the  
rest of the string to make sure the quotes pair up.  Ow.

This uses assertions to get around the whole-match nature of  
replaceText().

The \ + matches the spaces to be removed.  The (?x) allows me to use  
whitespace in the regex.

In the lines of the regex the part before the space matching is the  
lookbehind assertion and the part after is the lookahead assertion.

To create the regex, I'd use format() which allows a special \"  
notation for literals in the first parameter, but the usual '& quote  
&' method will also work.

This pairs quotes from the right, so if the quotes are not paired,  
this will goof up at the start of the string.

Dar Scott




More information about the use-livecode mailing list