J. Lev
J. Lev

Reputation: 317

Regex to match if a word starts and end with a letter, have no more than one consecutive non-letter (. *')

I'm currently trying to find a regex to match a specific use case and I'm not finding any specific way to achieve it. I would like, as the title says, to match if a word starts and end with a letter, contains only letter and those characters: "\ *- \'" . It should also have no more than one consecutive non-letter.

I currently have this, but it accepts consecutive non-letter and doesn't accept single letters [a-zA-Z][a-zA-Z \-*']+[a-zA-Z]

I want my regex to accept this string

Upvotes: 1

Views: 921

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

You may use

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

See the regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string anchor
  • [a-zA-Z]+ - 1+ ASCII letters
  • (?:[ *'-][a-zA-Z]+)* - 0 or more sequences of:
    • [ *'-] - a space, *, ' or -
    • [a-zA-Z]+ - 1+ ASCII letters
  • $ - end of string anchor.

Upvotes: 1

Related Questions