代码之家  ›  专栏  ›  技术社区  ›  Icemanind

以“Google”方式拆分字符串

  •  1
  • Icemanind  · 技术社区  · 15 年前

    我试图创建一个函数,将字符串拆分为搜索项。使用此代码可以正常工作:

    string TestString = "This is a test";
    string[] Terms;
    Terms = TestString.Split(" ");
    

    这将把我的字符串分成4个字符串:“This”、“is”、“a”、“test”。

    string TestString = "This \"test will\" fail";
    string[] Terms;
    Terms = TestString.Split(" ");
    

    这将把我的字符串分成4个字符串,同样是:“This”,“test”,“will”,“fail”

    有人知道怎么做吗?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Nicolas Bottarini    15 年前

    尝试使用正则表达式:

    var testString = "This \"test will\" fail";
    var termsMatches = Regex.Matches(testString, "(\\w+)|\"([\\w ]+[^ ])\"");