KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Trimming white space with Match regex
PRODUCT: 4D | VERSION: 11.6 | PLATFORM: Mac & Win
Published On: April 16, 2010

This sample code trims all leading and trailing white spaces from text. The input value is text with leading and trailing white spaces. The output is the trimmed string.

C_TEXT($myString; $1)
C_TEXT($0;$resultString;$resultString1)
C_TEXT($pattern)
C_LONGINT($start;$position;$length)
C_BOOLEAN($foundFlag)
$myString:=$1
$start:=1
$foundFlag:=False

  `regex pattern for leading white spaces
  `^ -- search the beginging of the string
  `\s+ -- search for one or more white spaces
$pattern:="^\s+"

$foundFlag:= Match regex($pattern; $myString; $start; $position; $length)
$resultString:=Substring($myString;$length+1)

  `regex pattern for trailing white spaces
  `$ -- search the end of the string
$pattern:="\s+$"

$foundFlag:=Match regex($pattern; $resultString; $start; $position; $length)
$resultString1:=Substring($resultString;$start;$position-1)

$0:=$resultString1


Commented by Barclay Berry on May 24, 2010 at 3:00 PM
I think you need to trap for your foundFlag. Currently you run the Replace String command regardless of finding a space.

For leading white space should be:

If (foundFlag)
$resultString:=Substring($myString;$length+1)
else
$resultString:=$myString
End if

And for the trailing white spaces:

If (foundFlag)
$resultString1:=Substring($resultString;$length+1)
else
$resultString1:=$resultString
End if
Commented by Chris Visaya on April 21, 2010 at 12:09 PM
Good catch, Walt. Thanks!
Commented by Walt Nelson on April 21, 2010 at 11:33 AM
Typo in the line:

$foundFlag:=Match regex($pattern;$resultSting;$start;$position;$length)

should be:

$foundFlag:=Match regex($pattern;$resultString;$start;$position;$length)