Search code examples
c#regex

Regex pattern to allow any ASCII chars. But not leading white spaces


I have to add a validation to a text box by writing a regex.

  • Characters can be any ASCII chars including special chars.
  • But it should not allow space or only spaces.
  • There can be spaces in between words and can also be a leading space.

I know "[^\s]" to validate for space. I know "^[\x00-\x7F]+$" to validate for ASCII Chars.

I want to combine these things to say i will allow ASCII chars including space but not just space or spaces.

Is there any way to do AND operation on this? or How to proceed? Any help would be appreciated.

Thanks in advance.


Solution

  • You can do that:

    ^(?> *)[\x00-\x7F]+$
    

    Since the eventual leading spaces are enclosed in an atomic group, you can be sure that the first character matched by [\x00-\x7F]+ can't be a space.