Find all words without numbers with RegEx

I found this code to get all the words of a string,

static string[] GetWords(string input) { MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b"); var words = from m in matches.Cast<Match>() where !string.IsNullOrEmpty(m.Value) select TrimSuffix(m.Value); return words.ToArray(); } static string TrimSuffix(string word) { int apostrapheLocation = word.IndexOf('\''); if (apostrapheLocation != -1) { word = word.Substring(0, apostrapheLocation); } return word; } 
  • Describe the code.
  • How can I get words without numbers?
+4
source share
2 answers

IN

 MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b"); 

the code uses a regular expression that will search for any word; \ b means the word boundary, and \ w is the POSIX alpha-numeric class to get everything as letters (with or without graphic accents), numbers, and sometimes underlining, and "just included in the list along with alphaNum. So image, basically it is a search for the beginning and end of the word and its choice.

then

 var words = from m in matches.Cast<Match>() where !string.IsNullOrEmpty(m.Value) select TrimSuffix(m.Value); 

is LINQ syntax where you can execute SQL-Like queries inside your code. This code gets each match from the regular expression and checks to see if the value is empty and get it without spaces. It can also add confirmation of your figure.

and this:

 static string TrimSuffix(string word) { int apostrapheLocation = word.IndexOf('\''); if (apostrapheLocation != -1) { word = word.Substring(0, apostrapheLocation); } return word; } 

removes "the words that have it, and gets only the part that is in front of it

i.e. for the word is not he will receive only don

+2
source

2 How can I get words without numbers?

You need to replace \w with [A-Za-z]

So your RegEx will be @"\b[A-Za-z']*\b"

And then you have to think about TrimSuffix (). RegEx allows apostrophes, but TrimSuffix () will only retrieve the left side. Thus, "this" will become "this."

+3
source

All Articles