Search code examples
regexregex-group

How to allow only 3 types of characters between words?


I have a set of allowed characters:

  1. apostrophe `

  2. empty space  

  3. dash -

I'm struggling with building a regex which:

a. allows only one occurrence of the allowed characters between each word (any number of words are allowed)

E.g.
text-text    --> VALID
text text    --> VALID
text`text    --> VALID

b. allows combinations of allowed characters but not one after the other

E.g.
text-text`text    --> VALID
text text-text    --> VALID
text`text text    --> VALID
text``text  text  --> INVALID
text`text  text   --> INVALID
text`text -text   --> INVALID

c. doesn't allow to start with empty space apostrophe ` or dash - and doesn't allow to end with apostrophe ` or dash - but can end with [emptyspace]

E.g.
text[emptyspace]  --> VALID
[emptyspace]text  --> INVALID
`text             --> INVALID
text`             --> INVALID
-text             --> INVALID
text-             --> INVALID

d. Special characters are not allowed at all

e. Digits are not allowed at all

This is what I have so far: https://regex101.com/r/9i3vq2/5


Solution

  • You may use

    ^[a-zA-Z]+(?:[ `-][a-zA-Z]+)* ?$
    

    See the regex demo

    Details

    • ^ - start of string
    • [a-zA-Z]+ - 1+ ASCII letters
    • (?:[ `-][a-zA-Z]+)* - 0 or more repetitions of
      • [ `-] - a space, backtick or -
      • [a-zA-Z]+ - 1+ ASCII letters
    • ? - an optional space
    • $ - end of string.