How to make some parts of a regex pattern conditional?

前端 未结 3 1506
野性不改
野性不改 2021-01-21 00:46

I checked this forum for a answer to my problem, but couldnt find. Experts please help.

I have a problem to validate a string say first name. I am given a set of rules w

3条回答
  •  忘掉有多难
    2021-01-21 01:02

    Try this

    [A-Za-z]+(?:[-'!` ]?[A-Za-z]+)?
    

    You can check it online here: regexr

    The second part

    (?:[-'!` ]?[A-Za-z]+)? 
    

    is a non capturing group, this group is because of the ? at the end optional.

提交回复
热议问题