August 2012
Intermediate to advanced
609 pages
19h 16m
English
You want to replace all matches of the regular expression ‹before› with the replacement text
«after».
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
}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, ...