May 2009
Intermediate to advanced
510 pages
15h
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, ...
Read now
Unlock full access