How to make some parts of a regex pattern conditional?

前端 未结 3 1457
野性不改
野性不改 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.

    0 讨论(0)
  • 2021-01-21 01:07

    Let Name be the regex for the simple name, Special the set of special characters (including the space). Then your final regex looks like

    Name(SpecialName)?
    
    0 讨论(0)
  • 2021-01-21 01:11

    What you need to do is repeat the text definition to have to exist 1 or more times AFTER the punctuation. This will work, but every name needs to be at least 2 characters (which seems reasonable..)

    [A-Za-z]+[-'!` ]?[A-Za-z]+

    0 讨论(0)
提交回复
热议问题