Javascript Regex - No White Space At Beginning + Allow Space in the Middle

Javascript regex - no white space at beginning + allow space in the middle

In your 2nd character class, \\s will match \ and s, and not \s. Thus it doesn't matches a whitespace. You should use just \s there. Also, move the hyphen towards the end, else it will create unintentional range in character class:

^[^-\s][a-zA-Z0-9_\s-]+$

Regular expression for no white space at start or end, but allow white space in middle, empty and any 6-20 characters?

You can use this regex:

^(?:\S.{4,18}\S)?$

Working Demo

In a RegEx I need to allow spaces only in middle and prevent spaces at beginning and end

I assume it is used in some kind of a RegularExpressionAttribute validation, and you just want to use a single pattern for this.

You have already the first building block:

[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]

This matches any char but the ones defined in the set. It does not match whitespace. If you quantify with * and wrap with anchors, no whitespace will be allowed anywhere in the string. So, you just need to add an optional group (quantified with * or ? or {x,y} depending on how many spaces you want to allow):

^[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+(?:\s[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+)*$
^^^ ^^

If you want to also match an empty string, wrap the pattern with an optional non-capturing group:

^(?:[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+(?:\s[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+)*)?$
^^^ ^^

Escape backslashes as needed.

As for the hyphen in the names: it might be appropriate to allow it in the same place as whitespace:

^(?:[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+(?:[\s-][^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+)*)?$
^^^^^

Regex that allows a single whitespace in the middle but with character limit.

You may use a positive lookahead here:

^(?=.{3,30}$)[A-Za-z0-9]+(?:\s[A-Za-z0-9]+)?$

See the regex demo.

Details:

  • ^ - start of string
  • (?=.{3,30}$) - there can be 3 to 30 chars (other than linebreak, replace the . with [A-Za-z0-9\s] to be more specific)
  • [A-Za-z0-9]+ - 1+ alphanumeric chars
  • (?:\s[A-Za-z0-9]+)? - an optional (1 or 0) occurrences of a

    • \s - whitespace
    • [A-Za-z0-9]+ - 1+ alphanumeric symbols
  • $ - end of string.

Regex Expression to not allow spacing at beginning

Try the following regex

^[a-zA-Z]+.*?[^\s]$

Explanation via Regex101. You can also test it there.

It matches the test cases you provided. Hope this helps!

Hogan



Related Topics



Leave a reply



Submit