检查字符串是否为字符串模式

时间:2013-04-08 19:40:09

标签: c#

我有以下字符串模式:

const string STRING_PATTERN = "Hello {0}";

如何检查字符串是否为上述字符串模式?

例如:

string" Hello World"是上述字符串模式

string" abc"不属于上述字符串模式。

最佳

2 个答案:

答案 0 :(得分:8)

使用正则表达式。

Regex.IsMatch(myString, "^Hello .+$")

或者@usr建议:

myString.StartsWith("Hello ")

答案 1 :(得分:2)

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      string txt="Hello World";

      string re1="(Hello)"; // Word 1
      string re2=".*?"; // Non-greedy match on filler
      string re3="((?:[a-z][a-z]+))";   // Word 2

      Regex r = new Regex(re1+re2+re3,RegexOptions.IgnoreCase|RegexOptions.Singleline);
      Match m = r.Match(txt);
      if (m.Success)
      {
            String word1=m.Groups[1].ToString();
            String word2=m.Groups[2].ToString();
            Console.Write("("+word1.ToString()+")"+"("+word2.ToString()+")"+"\n");
      }
      Console.ReadLine();
    }
  }
}
相关问题