【LABVIEW到C#】3》String的操作之Match Pattern Funtion.vi

本文介绍了一个C#中的正则表达式匹配类的实现,该类能够找到字符串中的匹配项并返回匹配前后的子串。通过实例演示了如何使用这个类进行字符串的匹配与分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/lucifer-mengxiaoxie/p/4316102.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值