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

前端 未结 8 1567
孤街浪徒
孤街浪徒 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:16

    Use Split().

    words = phrase.Split(' ');
    

    Without punctuation.

    words = phrase.Split(new Char [] {' ', ',', '.', ':', , ';', '!', '?', '\t'});
    
    0 讨论(0)
  • 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[] {' ', '.'});
    
    0 讨论(0)
提交回复
热议问题