Sanju Rao
Sanju Rao

Reputation: 331

Regex matching a string without whitespace and hash # character

I need to validate a text box to avoid the user to enter white space or hash tag #. As of now i tried below regular expressions and achieved only to restrict space.

Case 1: Regular expression restricting Space : ^\S+$ - This is working

Case 2: Regular expression to restrict Space and # hash tag - (\S+$)[!#] This is not working

I need to restrict the user entering white space and hash tag #.

Upvotes: 2

Views: 3633

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You need to unroll the \S as [^\s] and add the # to it:

^[^\s#]+$

See the regex demo.

Pattern details:

  • ^ - start of string anchor
  • [^\s#]+ - 1 or more (+) characters other than (see [^...], a negated character class) whitespace (\s) and # symbol
  • $ - end of string.

Upvotes: 4

Related Questions