c#学习笔记之字符串和正则表达式

一、字符串

c#中提供了一系列关于string类型的值的操作,便于我们对string进行各种类型的操作,例如比较,转化成字符串等等

eg:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace stringand
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 554;
            string stringa = a.ToString();//把a的内容以字符串形式输出

            string b = "qwer";
            string c = "asdf";
            Console.WriteLine(b.CompareTo(c));//比较string b和c的大小,若为正数,则前者大
            //若为0,则两者相等,若为负数,则后者大,此处返回1
            Console.WriteLine(string.Compare(b,c));// 返回1
        }
    }
}

另外,附上一些string类包含的方法

二、正则表达式

C#中为正则表达式的使用提供了非常强大的功能,这就是Regex类。这个包包含于System.Text.RegularExpressions命名空间下面。

eg:

Regex regex = new Regex(@"d");//  d为匹配数字

regex.IsMatch("abc"); //返回值为false,字符串中未包含数字
regex.IsMatch("abc3abc"); //返回值为true,因为字符串中包含了数字

regex.Matches("abc123abc").Count;//返回3,因为匹配到3个数字

regex.Match("abc123abc").Value;// 返回为1,因为是匹配到第一个数字的值

下面是在vs中的一些实例:

string s1 = "One,Two,Three Liberty Associates, Inc.";
             Regex theRegex = new Regex(" |, |,");
             StringBuilder sBuilder = new StringBuilder();  int id = 1;
             foreach (string subString in theRegex.Split(s1))
             {
                 sBuilder.AppendFormat("{0}: {1}
", id++, subString);
             }
             Console.WriteLine("{0}", sBuilder);

 string string1 = "This is a test string";
            // find any nonwhitespace followed by whitespa
             Regex theReg = new Regex(@"(S+)s");
             // get the collection of matches
             MatchCollection theMatches = theReg.Matches(string1);
              // iterate through the collection
             foreach (Match theMatch in theMatches)
             {
               Console.WriteLine("theMatch.Length: {0}", theMatch.Length);
               if (theMatch.Length != 0)
                  {
                     Console.WriteLine("theMatch: {0}", theMatch.ToString( ));
                 }
             }

结果为:

 string string2 = "04:03:27 127.0.0.0 LibertyAssociates.com " +
                 "04:03:28 127.0.0.0 foo.com " +  "04:03:29 127.0.0.0 bar.com ";
  
            Regex theReg2 = new Regex(@"(?<time>(d|:)+)s" 
                +@"(?<ip>(d|.)+)s" + @"(?<site>S+)");//  S :与任何非空白的字符匹配。
  
          MatchCollection theMatches2 = theReg2.Matches(string2);
          foreach (Match theMatch in theMatches2)
         {// iterate through the collection
              if (theMatch.Length != 0)
              {
                  Console.WriteLine("
theMatch: {0}", theMatch.ToString());
                 Console.WriteLine("time:{0}",theMatch.Groups["time"]);
                  Console.WriteLine("ip: {0}", theMatch.Groups["ip"]);
                  Console.WriteLine("site: {0}", theMatch.Groups["site"]);
             }
          }

结果为:

原文地址:https://www.cnblogs.com/zyqBlog/p/4438896.html