How do I split a phrase into words using Regex in C#

前端 未结 8 1605
孤街浪徒
孤街浪徒 2020-12-18 01:25

I am trying to split a sentence/phrase in to words using Regex.

var phrase = \"This isn\'t a test.\";
var words = Regex.Split(phrase, @\"\\W+\").ToList();
         


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-18 02:18

    You can try if you're trying to split based on spaces only.

    var words = Regex.Split(phrase, @"[^ ]+").ToList();
    

    The other approach is to add the apostrophe by adding that to your character class.

    var words = Regex.Split(phrase, @"(\W|')+").ToList();
    

    Otherwise, is there a specific reason that you cannot use string.Split()? This would seem much more straightforward. Also, you would also be able to pass in other punctuation characters (i.e. split on . as well as spaces).

    var words = phrase.Split(' ');
    var words = phrase.Split(new char[] {' ', '.'});
    

提交回复
热议问题