-2

我有以下字符串模式:

const string STRING_PATTERN = "Hello {0}";

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

例如:

字符串“Hello World”是上述字符串模式

字符串“abc”不属于上述字符串模式。

最好的

4

2 回答 2

8

使用正则表达式。

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

或如@usr 建议的那样:

myString.StartsWith("Hello ")
于 2013-04-08T19:43:49.323 回答
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();
    }
  }
}
于 2013-04-08T19:45:18.610 回答