c# 正则表达式 匹配

2024-11-07 07:51:50
推荐回答(2个)
回答(1):

(?\d*) 取命名组nums

RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"(?\d*)", options);
string input = @"*pp22";

// Check for match
bool isMatch = regex.IsMatch(input);
if( isMatch )
{
// TODO: Do something with result
System.Windows.Forms.MessageBox.Show(input, "IsMatch");
}

// Get match
Match match = regex.Match(input);
if( match != null )
{
// TODO: Do something with result
System.Windows.Forms.MessageBox.Show(match.Value, "Match");
}

// Get matches
MatchCollection matches = regex.Matches(input);
for( int i = 0; i != matches.Count; ++i )
{
// TODO: Do something with result
System.Windows.Forms.MessageBox.Show(matches[i].Value, "Match");
}

// Numbered groups
for( int i = 0; i != match.Groups.Count; ++i )
{
Group group = match.Groups[i];

// TODO: Do something with result
System.Windows.Forms.MessageBox.Show(group.Value, "Group: " + i);
}

// Named groups
string groupA = match.Groups["nums"].Value;

// TODO: Do something with result
System.Windows.Forms.MessageBox.Show(groupA, "Group: nums");

}

回答(2):

写个方法,返回值类型用bool类型,参数是字符串类型,当匹配上的时候返回值是true,否则返回false,调用的时候,只需要传入字符串就可以判断