Regex for string cleaning

Kuler Master 416 Reputation points
2022-07-14T12:32:57.963+00:00

Hi there,

I have the following string to be cleaned of 1 and 2 character words unless it's the letter M or F.

EL EL EL EL M EL EL FU S FF EL EL EL E EL

I tried with the following expression but it didn't work quite well.

var output = Regex.Replace(input, @"\b\w{2}\s", "").Trim();  

I ended up with "M S E EL"

Could you help me so I can end up with only M?

Would be greatly appreciated. Thanks

Developer technologies | VB
Developer technologies | .NET | .NET CLI
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

Developer technologies | ASP.NET Core | Other
0 comments No comments

Answer accepted by question author
Viorel 127.3K Reputation points
2022-07-14T13:36:21.243+00:00

To consider letters only, try this: @"\b(\p{L}{2}|[^MF\s])\b\s*".

Was this answer helpful?

1 person found this answer helpful.

5 additional answers

Sort by: Newest
  1. Viorel 127.3K Reputation points
    2022-07-14T12:42:18.343+00:00

    Check this pattern: @"\b(\w{2,}|[^MF\s])\b\s*".

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.