开发者

Splitting strings in a "Google" style way

I am trying to create a function that will split a string into search terms. Using this code will work fine:

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

This will split my string into 4 strings: "This", "is", "a", "test". However I want words that are enclosed in quotes to be treated as one word:

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

This will split my string into 4 strings, again: "This", "\"test", "will\"", "fail"

What I want i开发者_运维问答s for it split that last string into only 3 strings: "This", "test will", "fail"

Anyone have any idea on how to do this?


Try using a Regex:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜