user2921139
user2921139

Reputation: 1789

Regex for one or more words separated by spaces

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}

Upvotes: 44

Views: 121840

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174874

I think you need something like this,

^\s*[A-Za-z0-9]+(?:\s+[A-Za-z0-9]+)*\s*$

DEMO

OR

^(?:\s+[A-Za-z0-9]+)+\s+$

DEMO

Upvotes: 13

mvp
mvp

Reputation: 116447

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.

Upvotes: 69

Related Questions