Skip to content

Instantly share code, notes, and snippets.

@wvpv
Last active February 7, 2022 10:41
Show Gist options
  • Save wvpv/a0f63889a291a27533dd to your computer and use it in GitHub Desktop.
Save wvpv/a0f63889a291a27533dd to your computer and use it in GitHub Desktop.
SFMC AMPScript RegEx
%%[
var @s, @o, @p, @m
output(concat("<br>Strip leading zeroes from a string"))
set @s = "0000012345"
set @p = "^0*(\d+)$"
set @o = RegExMatch(@s, @p, 1)
output(concat("<br>input: ", @s))
output(concat('<br>pattern: "', @p, '"'))
output(concat("<br>output: ", @o))
output(concat("<br><br>Check for all digits, no match"))
set @s = "12345x"
set @p = "^\d*$"
set @o = RegExMatch(@s, @p, 0)
output(concat("<br>input: ", @s))
output(concat('<br>pattern: "', @p, '"'))
output(concat("<br>output: ", @o))
output(concat("<br><br>Check for all digits, match"))
set @s = "12345"
set @p = "^\d*$"
set @o = RegExMatch(@s, @p, 0)
output(concat("<br>input: ", @s))
output(concat('<br>pattern: "', @p, '"'))
output(concat("<br>output: ", @o))
output(concat("<br><br>Replace parenthetical text with space"))
set @s = "whee (whatever it is) whoop"
set @p = "\s\(.+\)\s"
set @m = RegExMatch(@s, @p, 0, "IgnoreCase")
set @o = replace(@s, @m, " ")
output(concat("<br>input: ", @s))
output(concat('<br>pattern: "', @p, '"'))
output(concat("<br>match: ", @m))
output(concat("<br>replaced: ", @o))
]%%
@Shahzad6077
Copy link

Hey @wvpv, is there any way to replace all occurrences with RegExMatch? this is only replacing the first occurrence.

@wvpv
Copy link
Author

wvpv commented Feb 5, 2022

The last example replaces all instances. Here's an updated string that illustrates it: https://mcsnippets.herokuapp.com/s/P8FlARhL

@Shahzad6077
Copy link

Shahzad6077 commented Feb 5, 2022

Actually, I want to replace all even or odd occurrences in a string with *(asterisk).

e.g
input: Testing Text
output: T*s*i*g T*x*

I came up with this regex: (?<!^(?:\S\S|\s\S|\S\s)*).

but the RegExMatch only replaces the first occurrence e.g T*sting Text

Here you can see It's working: https://regex101.com/r/mXKvqn/1
It's not working with RegExMatch: https://mcsnippets.herokuapp.com/s/6LXtg4Y3

@wvpv
Copy link
Author

wvpv commented Feb 5, 2022

Why bend your mind with a regex when you can use a loop and the mod function to detect odd/even?

https://mcsnippets.herokuapp.com/s/n3wtVxJP

@Shahzad6077
Copy link

Yeah looks great, Thanks Adam.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment