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
Data:
doc.Params["model"] = new {
text = "Product ABC123 costs $45.99"
};
Output:
<p>Product ABC costs $.</p>
Mask Phone Numbers
Data:
doc.Params["model"] = new {
phone = "555-123-4567"
};
Output:
<p>XXX-XXX-XXXX</p>
Replace Multiple Spaces
Data:
doc.Params["model"] = new {
text = "Too many spaces"
};
Output:
<p>Too many spaces</p>
Sanitize Special Characters
Data:
doc.Params["model"] = new {
filename = "My File (2024)!.pdf"
};
Output:
<p>My_File__2024__.pdf</p>
Format Numbers with Separators
Remove HTML Tags
Data:
doc.Params["model"] = new {
html = "<strong>Bold</strong> and <em>italic</em> text"
};
Output:
<p>Bold and italic text</p>
Convert Dates
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 |