Regular Expressions in AMPScript

Did you know you can use regular expressions in AMPScript?

You can.

Here are some RegExMatch() snippets that I’ve used:

Variables

@s = input string
@p = pattern
@m = match
@o = output

Sample Code

%%[
var @s, @o, @p, @m

outputLine(concat("<h4>Strip leading zeroes from a string</h4>"))
set @s = "0000012345"
set @p = "^0*(\d+)$"
set @o = RegExMatch(@s, @p, 1)
outputLine(concat("input:  ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("output: ",@o,"<br>"))

outputLine(concat("<h4>Check for all digits, no match</h4>"))
set @s = "12345x"
set @p = "^\d*$"
set @o = RegExMatch(@s, @p , 0)
outputLine(concat("input: ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("output: ",@o,"<br>"))

outputLine(concat("<h4>Check for all digits, match</h4>"))
set @s = "12345"
set @p = "^\d*$"
set @o = RegExMatch(@s, @p , 0)
outputLine(concat("input: ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("output: ",@o,"<br>"))

outputLine(concat("<h4>Replace parenthetical text with space</h4>"))
set @s = "whee (whatever it is) whoop"
set @p = "\s\(.+\)\s"
set @m = RegExMatch(@s, @p, 0 , "IgnoreCase")
set @o = replace(@s,@m, " ")
outputLine(concat("input:  ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("match: ",@m,"<br>"))
outputLine(concat("replaced: ",@o,"<br>"))

]%%

Output

Strip leading zeroes from a string

input: 0000012345
pattern: “^0*(\d+)$”
output: 12345

Check for all digits, no match

input: 12345x
pattern: “^\d*$”
output:

Check for all digits, match

input: 12345
pattern: “^\d*$”
output: 12345

Replace parenthetical text with space

input: whee (whatever it is) whoop
match: (whatever it is)
pattern: “\s\(.+\)\s”
output: whee whoop

For further reading

RegExMatch() function
Concat() function
OutputLine() function
RegEx pattern reference
RegEx options reference