Replaces all occurrences of a specified character or string in this instance with another specified character or string. | |
ToString | Converts the value of a StringBuilder to a String . |
Regular Expressions
When dealing with strings, you often need to perform checks on them to see if they match certain patterns. For example, if your application requires the user to enter an email address so that you can send them a confirmation email later on, it is important to at least verify that the user has entered a correctly formatted email address. To perform the checking, you can use the techniques that you have learnt earlier in this chapter by manually looking for specific patterns in the email address. However, this is a tedious and mundane task.
A better approach would be to use regular expressions — a language for describing and manipulating text. Using regular expressions, you can define the patterns of a text and match it against a string. In the .NET Framework, the System.Text.RegularExpressions
namespace contains the RegEx
class for manipulating regular expressions.
Searching for a Match
To use the RegEx
class, first you need to import the System.Text.RegularExpressions
namespace:
using System.Text.RegularExpressions;
The following statements shows how you can create an instance of the RegEx class, specify the pattern to search for, and match it against a string:
string s = 'This is a string';
Regex r = new Regex('string');
if (r.IsMatch(s)) {
Console.WriteLine('Matches.');
}
In this example, the Regex
class takes in a string constructor, which is the pattern you are searching for. In this case, you are searching for the word 'string' and it is matched against the s string variable. The IsMatch()
method returns True
if there is a match (that is, the string s contains the word 'string').
To find the exact position of the text 'string' in the variable, you can use the Match()
method of the RegEx
class. It returns a Match
object that you can use to get the position of the text that matches the search pattern using the Index property:
string s = 'This is a string';
Regex r = new Regex('string');
if (r.IsMatch(s)) {
Console.WriteLine('Matches.');
}
What if you have multiple matches in a string? In this case, you can use the Matches()
method of the RegEx
class. This method returns a MatchCollection
object, and you can iteratively loop through it to obtain the index positions of each individual match:
Regex r = new Regex('string');
MatchCollection mc = r.Matches(s);
More Complex Pattern Matching
You can specify more complex searches using
string gender = 'Mr Wei-Meng Lee';
Regex r = new Regex('Mr|Mrs');
if (r.IsMatch(gender)) {
Console.WriteLine('Matches.');
}
The following table describes regular expression operators commonly used in search patterns.
Operator | Description |
---|---|
. | Match any one character |
[ ] | Match any one character listed between the brackets |
[^ ] | Match any one character not listed between the brackets |
? |