C # regex delete words less than 3 letters?

Any ideas on regex should remove words of less than 3 letters? So he will find “ii it was a bbb cat rat hat” etc. But not “four, three, two”.

+3
source share
4 answers

I'm going to go on a limb and throw you an irregular solution:

public static string StripWordsWithLessThanXLetters(string input, int x)
{
    var inputElements = input.Split(' ');
    var resultBuilder = new StringBuilder();
    foreach (var element in inputElements)
    {
        if (element.Length >= x)
        {
            resultBuilder.Append(element + " ");
        }
    }
    return resultBuilder.ToString().Trim();
}

This is more detailed than other solutions, but I think that the cost of using the Linq solution can outweigh its net benefits, and regexing carries the same costs (potentially with greater complexity for maintenance).

0
source

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

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

, :

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

(Altho / .)

+7

, linq.

string[] words = inputString.Split(' ');

var longWords = words.Where(x => x.Length > 3);

string outputString = String.Join(" ", longWords.ToArray());

Hell, you can even do this in one line of code:

outputString = String.Join(" ", inputString.Split(' ').Where(x => x.Length > 3).ToArray());
+5
source
string qText = "Long or not long sample text";
var inputWords = qText.Split(' ').ToList();
var rem = (from c in inputWords
           where c.Length > 3
           select c).ToList();
0
source

All Articles