Search code examples
javascriptregexstringregex-greedy

RegEx for passing space and single quote


I'm fairly new to RegEx's and am having some issues getting my RegEx to do what I'd like it to. I'm attempting to create a RegEx that prevents any special character OTHER THAN single quote ('), dash (-), and period (.). The RegEx needs to allow spaces, and empty strings.

What I have for now is:

^[a-zA-Z0-9-.]*$

What would I need to add in order to make it work for example the name "Kevin O'Leary"?

I've attempted to allow spaces by adding \s, but it broke other parts of my RegEx.

^[a-zA-Z0-9-.]*$

Expected: Should allow names like Kevin O'Leary Actual: Does not allow names like Kevin O'Leary


Solution

  • Simply add a quote and a space to the character range:

    ^[ a-zA-Z0-9'.-]*$
    

    The space can simply be a literal space in the pattern. Also, you need to have the - as the last symbol, because it has a special meaning in ranges.

    regex101 demo