Tech Tip: Method for capitalizing the first letter of each word with Regex
PRODUCT: 4D | VERSION: 12.1 | PLATFORM: Mac & Win
Published On: April 1, 2011
Recently a Tech Tip was published for with a method for capitalizing the first letter of each word.
That method views the characters space, carriage return, and line feed as word breaks. The following method uses Regular Expressions to handle these searches instead of a For statement going through the entire string.
This method improves on the performance of the original by using Regular Expressions so a For loop does not have to go through each character in the source string. It improves on the results by using a standardized definition of white space: the "\b" Regular Expressions word boundary. Three different position qualify as word boundaries:
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
The following method shows how to use the Regex word boundaries to parse out whole words only, then capitalizes each whole word:
//Method: UTIL_capitalizeFirst_Regex //Inputs: $1 -> String -> String to capitalize //Output: $0 -> String -> Capitalized string //Description: //The method capitalizes the first letter of every word //using the Match regex command C_LONGINT($posf;$lengf;$start) C_TEXT($regex;$to_upper;$1;$0) C_BOOLEAN($match) $regex:="\\b(\\w)+\\b" $to_upper:=$1 $start:=1 $match:=True While ($match=True) $match:=Match regex($regex;$to_upper;$start;$posf;$lengf) $start:=$posf+$lengf If ($match=True) $to_upper[[$posf]]:=Uppercase($to_upper[[$posf]]) End if End while $0:=$to_upper |
Here is a sample call to that method:
$capitalized:=UTIL_capitalizeFirst_Regex($mystring) |