Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Regex remove words of less than 3 letters?

Tags:

c#

regex

Any ideas on the regex need to remove words of 3 letters or less? So it would find "ii it was bbb cat rat hat" etc but not "four, three, twos".

like image 853
user685590 Avatar asked Dec 07 '22 21:12

user685590


1 Answers

Regex to match words of length 1 to 3 would be \b\w{1,3}\b, replace these matches with empty string.

Regex re = new Regex(@"\b\w{1,3}\b");
var result = re.Replace(input, "");

To also remove double spaces you could use:

Regex re = new Regex(@"\s*\b\w{1,3}\b\s*");
var result = re.Replace(input, " ");

(Altho it will leave a space at the beginning/end of string.)

like image 66
Qtax Avatar answered Dec 09 '22 09:12

Qtax