2

I want to check if a string hast 0...n whitespace, one * and 0...n whitespace.

The pattern

 var derefpatt = new RegExp("\\s*\\*\\s*");  
 var res2 = derefpatt.test(string); 

is true if string is " ** " but it should be only true if string is " * "

What is wrong?

Regards

Alex

1
  • is n the same for both whitespace ? Commented Apr 10, 2015 at 17:07

1 Answer 1

2

For:

  • 0...n whitespace -> \s*
  • one * -> \*
  • 0...n whitespace -> \s*

You can use this regex (notice the usage of anchors ^ and $):

^\s*\*\s*$

Regular expression visualization

On the other hand, if you want the same amount of spaces, you can use:

^(\s*)\*\1$
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks... var derefpatt = new RegExp("^\\s*\*\\s*$"); works. But why "\\s*\*\\s*" without ^ and $ doesn't work?
Because RegExp.test() doesn't check whether the whole string matches, it checks for any substring within the string that matches and returns true if it finds any. Since there are 0 characters of whitespace between the asterisks, it fulfills the condition of 0 characters of whitespace after an asterisk.

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.