C# string manipulation with Regex

First of all, we need to know something about C# string interpretation since Regular expression use a lot ‘\’ of symbol like that to define itself.

For example, if you want a double quote in your definition, use \” or “”. if you want \, use \\ .

Here is a complete example. “^=\”\\d{8}\”$” in C# is actually ^=”\d{8}”$ for regular expression.

Of course, if your definition didn’t contain double quote, you can use C# @ symbol to define your regular expression to simplify the job.

Then I am going to demonstrate a very common thing that people want to do with regular expression beside verifying pattern. Which is getting the substring that matches the pattern.

Regex l_pattern = new Regex(RegexPatternString);
Match l_match = l_pattern.Match(TheInputString);
string l_matchString = l_match.value;

l_matchString is the string that matches the given pattern.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s