Reputation: 317
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
This is accepted since it contains only spaces and letter and there is no consecutive space
a
should be accepted
This is --- not accepted because it contains 5 consecutive non-letters characters
(3 dashes and 2 spaces)
" This is not accepted because it starts with a space"
Neither is this one since it ends with a dash -
Upvotes: 1
Views: 921
Reputation: 627292
You may use
^[a-zA-Z]+(?:[ *'-][a-zA-Z]+)*$
See the regex demo and the regex graph:
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