C # Regular Expression match related string __ Regular expression
Source: Internet
Author: User
#正则表达式匹配字符串的方法如下:
1. Use regular expression System.Text.RegularExpressions namespaces in C #;
2. Use the regular expression matches () method in C # to match a string with the following format:
MatchCollection matches = regex.matches (Str, pattern, regexoptions.ignorecase | Regexoptions.explicitcapture);
Where str represents the input string, pattern represents the match mode, regexoptions.ignorecase indicates that the case is ignored, and Regexoptions.explicitcapture indicates that the collection matching method is changed.
3. The matching results are saved in the MatchCollection collection and can be iterated through the result set to remove the result of the match object.
TestRagular.cs:
Using System;
Using System.Text.RegularExpressions;
Namespace Magci.Test.Strings
{
public class Testregular
{
public static void Writematches (String str, matchcollection matches)
{
Console.WriteLine ("\nstring is:" + str);
Console.WriteLine ("No.") of matches: "+ matches." Count);
foreach (Match nextmatch in matches)
{
Take out a matching string and up to 10 peripheral characters
int Index = Nextmatch.index;
string result = Nextmatch.tostring ();
int charsbefore = (Index < 5)? Index:5;
int fromend = str. Length-index-result. Length;
int charsafter = (Fromend < 5)? Fromend:5;
int charstodisplay = Charsbefore + result. Length + charsafter;
Find words that start with "M" and End with "C"
Pattern = @ "\bm\s*c\b";
matches = regex.matches (Str, pattern, regexoptions.ignorecase | Regexoptions.explicitcapture);
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service