Skip to main content Link Search Menu Expand Document (external link)

regexSwap() : Replace Using Regular Expression


On this page

Summary

Replace all occurrences matching a regular expression pattern with a replacement string.

Signature

regexSwap(str, pattern, replacement)

Parameters

Parameter Type Required Description
str String Yes The source string
pattern String Yes The regular expression pattern
replacement String Yes The replacement text

Returns

Type: String

The string with all pattern matches replaced.


Examples

Remove All Digits


<p>{{regexSwap(model.text, '\\d', '')}}</p>

Data:

doc.Params["model"] = new {
    text = "Product ABC123 costs $45.99"
};

Output:

<p>Product ABC costs $.</p>

Mask Phone Numbers


<p>{{regexSwap(model.phone, '\\d', 'X')}}</p>

Data:

doc.Params["model"] = new {
    phone = "555-123-4567"
};

Output:

<p>XXX-XXX-XXXX</p>

Replace Multiple Spaces


<p>{{regexSwap(model.text, '\\s+', ' ')}}</p>

Data:

doc.Params["model"] = new {
    text = "Too    many     spaces"
};

Output:

<p>Too many spaces</p>

Sanitize Special Characters


<p>{{regexSwap(model.filename, '[^a-zA-Z0-9_.-]', '_')}}</p>

Data:

doc.Params["model"] = new {
    filename = "My File (2024)!.pdf"
};

Output:

<p>My_File__2024__.pdf</p>

Format Numbers with Separators


<p>{{regexSwap(model.number, '(\\d)(?=(\\d{3})+$)', '$1,')}}</p>

Remove HTML Tags


<p>{{regexSwap(model.html, '<[^>]+>', '')}}</p>

Data:

doc.Params["model"] = new {
    html = "<strong>Bold</strong> and <em>italic</em> text"
};

Output:

<p>Bold and italic text</p>

Convert Dates


<!-- Convert MM/DD/YYYY to YYYY-MM-DD -->
<p>{{regexSwap(model.date, '(\\d{2})/(\\d{2})/(\\d{4})', '$3-$1-$2')}}</p>

Data:

doc.Params["model"] = new {
    date = "03/15/2024"
};

Output:

<p>2024-03-15</p>

Notes

  • Uses .NET regex syntax
  • Replaces all occurrences (not just first)
  • Backslashes must be escaped: \\d, \\w, etc.
  • Supports capture groups: $1, $2, etc.
  • For simple replacement, replace() is faster
  • More powerful but slower than replace()
  • Returns original string if pattern doesn’t match

Common Patterns

Pattern Replacement Description
\\s+ ' ' Normalize whitespace
\\d 'X' Mask digits
<[^>]+> '' Remove HTML tags
[^a-zA-Z0-9] '_' Replace special chars
(\\d{3})(\\d{3})(\\d{4}) '($1) $2-$3' Format phone

See Also