0

How to check if a string contains a pattern separated by whitespace?

Examples:

"abc  ef    ds       ab  "

Now I would like to check if the given string consists only of the pattern [a-z] separated by whitespace. My try: ^\s*[a-z]*\s*$. But this checks only whitespace in the beginning and end, not if the whitespaces is used for separation of the content.

4
  • What do you mean by pattern seperated? It means 2 whitespace then 3 then 4 etc..? Commented Jan 18, 2014 at 12:38
  • The whitespace between pattern [a-z] can be arbritrary. Commented Jan 18, 2014 at 12:41
  • Would " " be a valid string? Or "abc"? Commented Jan 18, 2014 at 12:41
  • @TimPietzcker Yes, both are valid. Commented Jan 18, 2014 at 12:42

2 Answers 2

3

Try this regular expression:

/^[a-z\s]+$/
Sign up to request clarification or add additional context in comments.

1 Comment

And now that we know even a single space is valid, this is the best answer.
1
^(\s|[a-z])*$

Zero or more case characters that are either whitespace, or A-Z.

If you want to make sure there's at least one thing other than white space, then:

^\s*[a-z]+(\s*|[a-z])*$

Zero or more whitespace, at least one character A-Z, then the same as above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.