Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for one or more words separated by spaces

Tags:

regex

I am looking for a regex where i have one or more words (possibly should cover alpha numeric also) separated by spaces (one or more spaces)

  1. " Test This stuff "
  2. " Test this "
  3. " Test "

Above are some examples of it

I wrote a regex to see what is repeating for #1

\s*[a-zA-Z]*\s*[a-zA-Z]*\s*[a-zA-Z]*\s* 

so i wanted to do something like {3} for repeating section.

But it does not seem to work.. I cant believe it is this difficult.

(\s*[a-zA-Z]*){3} 
like image 641
user2921139 Avatar asked Aug 05 '14 05:08

user2921139


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

Are spaces allowed in regex?

Yes, also your regex will match if there are just spaces. My reply was to Neha choudary's comment. @Pierre Three years later -- I came across this question today, saw your comment; I use regex hero (regexhero.net) for testing regular expressions.

How do you indicate a space in regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

What does \d do in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).


1 Answers

If you do not care just how many words you have, this would work:

[\w\s]+ 

\w is any alphanumeric. Replace it with a-zA-Z if you need only letters.

like image 142
mvp Avatar answered Sep 24 '22 01:09

mvp