3.14. Replace All Matches
Problem
You want to replace all matches of the regular expression ‹before
› with the replacement text
«after
».
Solution
C#
You can use the static call when you process only a small number of strings with the same regular expression:
string resultString = Regex.Replace(subjectString, "before", "after");
If the regex is provided by the end user, you should use the static call with full exception handling:
string resultString = null; try { resultString = Regex.Replace(subjectString, "before", "after"); } catch (ArgumentNullException ex) { // Cannot pass null as the regular expression, subject string, // or replacement text } catch (ArgumentException ex) { // Syntax error in the regular expression }
Construct a Regex
object if you want to use the same regular expression with a large
number of strings:
Regex regexObj = new Regex("before"); string resultString = regexObj.Replace(subjectString, "after");
If the regex is provided by the end user, you should use the
Regex
object with full exception handling:
string resultString = null; try { Regex regexObj = new Regex("before"); try { resultString = regexObj.Replace(subjectString, "after"); } catch (ArgumentNullException ex) { // Cannot pass null as the subject string or replacement text } } catch (ArgumentException ex) { // Syntax error in the regular expression }
VB.NET
You can use the static call when you process only a small number of strings with the same regular expression:
Dim ResultString = Regex.Replace(SubjectString, ...
Get Regular Expressions Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.