Home > Net >  How to add the option to allow only one space in a regex
How to add the option to allow only one space in a regex

Time:02-16

I want a regex that will allow only one space within a set of characters. I have the below regex which doesn't accept space. The below regex only supports strings like

1. @alia 2. @ranbir 3. @shilpa

const regex = /@(\w ([a-z]|[A-Z]|[0-9]|[-]|[_]|[.]|['])*)$/g;

I want a regex that will allow strings like

1. @alia bhat 2. @ranbir kapoor 3. @shilpa shetty

CodePudding user response:

You can try something like this:

@([\w\-\.\'] (?:\s[\w\-\.\'] )?)$

Explanation: group all the chars in a single set (\w = a-zA-Z0-9_ the rest of the chars)

then a next group would optionally match a single space followed by at least one character of the same set of characters, this means that your current single words will match and also two words but not if there is two spaces or just a single space at the end

Working example: enter image description here

CodePudding user response:

You can use regex alternative. First alternative is accepting the space and second is your original regex.

/@(\w  \w |\w )/g
  • Related