How to Use Regex.IsMatch in C# for Pattern Matching
Use
Regex.IsMatch(string input, string pattern) in C# to check if the input string matches the given regular expression pattern. It returns true if the pattern is found and false otherwise.Syntax
The Regex.IsMatch method checks if a string matches a regular expression pattern.
input: The string you want to test.pattern: The regular expression pattern to match.- Returns
trueif the pattern matches anywhere in the input string; otherwise,false.
csharp
bool isMatch = Regex.IsMatch(input, pattern);
Example
This example shows how to check if a string contains only digits using Regex.IsMatch. It prints Match found! if the input matches the pattern.
csharp
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "12345"; string pattern = "^\\d+$"; // Matches only digits from start to end bool isMatch = Regex.IsMatch(input, pattern); if (isMatch) { Console.WriteLine("Match found!"); } else { Console.WriteLine("No match."); } } }
Output
Match found!
Common Pitfalls
Common mistakes when using Regex.IsMatch include:
- Not escaping special characters in the pattern properly.
- Using patterns that match partially when full match is needed (use anchors like
^and$). - Confusing
Regex.IsMatchwith methods that return matched text.
Example of a wrong and right pattern:
csharp
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "abc123"; // Wrong: pattern missing anchors, matches anywhere bool wrongMatch = Regex.IsMatch(input, "123"); Console.WriteLine(wrongMatch); // True, but partial match // Right: pattern with anchors for full match bool rightMatch = Regex.IsMatch(input, "^abc123$"); Console.WriteLine(rightMatch); // True, full match } }
Output
True
True
Quick Reference
Tips for using Regex.IsMatch:
- Use
^and$to match the whole string. - Escape special characters like
\,.,?in patterns. - Use verbatim strings
@"pattern"to avoid double escaping. - Remember it returns a boolean, not the matched text.
Key Takeaways
Regex.IsMatch returns true if the input string matches the given pattern anywhere.
Use anchors ^ and $ to ensure the entire string matches the pattern.
Escape special regex characters properly or use verbatim strings for patterns.
Regex.IsMatch only tells if a match exists; it does not return the matched text.
Common mistakes include missing anchors and incorrect escaping.