C#实现如下
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace DEMO { class Darrenstring { public class Matchpattern:Darrenstring { private string text; private string pattern; private int index; public bool ismatch; public Matchpattern(string Text, string Pattern) { text = Text; pattern = Pattern; Match a = Regex.Match(text,pattern); index=a.Index; ismatch = a.Success; } public int Index() { return index; } public string Before() { if (ismatch) { return (text.Substring(0, index)); } else return null; } public string After() { if (ismatch) { return (text.Substring(index + pattern.Length, text.Length - pattern.Length-index)); } else return null; } } } }
类写好后 我们来做个试验 新建个winform程序
程序部分代码如下:
private void Confirm_Click(object sender, EventArgs e) { Darrenstring.Matchpattern A = new Darrenstring.Matchpattern(Source.Text, Terminal.Text); //Terminal.Text = Convert.ToString(A.Index()); before1.Text = A.Before(); After.Text = A.After(); IsMatched.Checked = A.ismatch; }
运行后结果图如下:
效果不错功能实现
MSDN资料参考
System.String.RegularExpressions命名空间说明 https://msdn.microsoft.com/zh-cn/library/System.Text.RegularExpressions(v=vs.80).aspx
Regex类说明 https://msdn.microsoft.com/zh-cn/library/system.text.regularexpressions.regex(v=vs.80).aspx
时间: 2024-10-03 07:56:04