简体   繁体   中英

Regex Match special characters between two characters

So I have the following requirements:

  1. Any alphabets between az or AZ
  2. The first character must be alphabet
  3. No numeric characters are allowed
  4. No special characters are allowed except these three: .-'
  5. And they can only be in between letters

So far, to solve this I have got the 2 following regex:

^[a-zA-Z][a-zA-Z ]*$

This is to solve points 1,2,3

(?<=[a-zA-Z])[.\-'](?=[a-zA-Z])

and this is to solve points 4,5

Test cases can be words like:

  • abc (pass)
  • abc's (pass)
  • abc' (fail)
  • abc ' (fail)

However I am unable to combine them. I have tried and I do not get the expected outcome. Any ideas?

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 occurrences of
    • [-.'] - a hyphen, dot or single quote
    • [a-zA-Z]+ - 1+ ASCII letters
  • $ - end of string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM