首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#操作字符串,该如何处理

2013-07-04 
C#操作字符串“高护32班 班主任:吴会长 (2007-2008学年第一学期)” 这个字符串我怎么样才能用C#得到“高护32

C#操作字符串
“高护32班 班主任:吴会长 (2007-2008学年第一学期)” 这个字符串我怎么样才能用C#得到“高护32班” “2007-2008” “一” 这三个字符串呢?
[解决办法]
问问wuyazhe正则能不能写……
[解决办法]

            //提供的字符串特征:
            //班级位于行首,并后跟空白字符
            System.Text.RegularExpressions.Regex regClass = new System.Text.RegularExpressions.Regex(@"^\S+",
                 System.Text.RegularExpressions.RegexOptions.Multiline);
            //在校周期以“-”连接两个数字
            System.Text.RegularExpressions.Regex regPeriod = new System.Text.RegularExpressions.Regex(@"\d+\-\d+",
                 System.Text.RegularExpressions.RegexOptions.Multiline);

            string sToMatch = "高护32班 班主任:吴会长 (2007-2008学年第一学期)";
            System.Text.RegularExpressions.Match match = regClass.Match(sToMatch);
            if (match != null)
                Console.WriteLine("班组:" + match.Value);
            match = regPeriod.Match(sToMatch);
            if (match != null)
                Console.WriteLine("在校周期:" + match.Value);

输出:
班组:高护32班
在校周期:2007-2008

[解决办法]
            //提供的字符串特征:
            //班级位于行首,并后跟空白字符


            //周期以“-”连接两个数字
            //“一”字夹在“第”和“学期”中间
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(
                @"^(?<class>\w+).+?(?<period>\d+\-\d+).+第(?<sp>\w)学期",
                 System.Text.RegularExpressions.RegexOptions.Multiline);

            string sToMatch = "高护32班 班主任:吴会长 (2007-2008学年第一学期)";
            System.Text.RegularExpressions.Match match = reg.Match(sToMatch);
            if (match != null)
                Console.WriteLine("班组:" + match.Groups["class"].Value
                    + "\r\n周期:" + match.Groups["period"].Value 
                    + "\r\n学期:" + match.Groups["sp"].Value);


班组:高护32班
周期:2007-2008
学期:一

[解决办法]
(\w+)[\s\S]*?(\(
[解决办法]
()(\d+-\d+)[\s\S]*?第([\s\S]*?)学期(\)
[解决办法]
))

取Groups[1].Value
[解决办法]
引用:
(\w+)[\s\S]*?(\(
[解决办法]
()(\d+-\d+)[\s\S]*?第([\s\S]*?)学期(\)
[解决办法]
))

取Groups[1].Value

勉强这样,但是不靠谱
(\w+)[\s\S]*?(\(
[解决办法]
()(\d+-\d+)[\s\S]*?第([\s\S]*?)学期(\)
[解决办法]
))

取Groups[1].Value
Groups[3].Value
Groups[4].Value
[解决办法]
str.Split(' ')[0] “高护32班” 


str.Split(' ')[3].Substring(1,9)  “2007-2008”
str.Split(' ')[3].Substring(13,1) “一” 

热点排行