Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make some parts of a regex pattern conditional?

Tags:

regex

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 which the string needs to honor and the same needs to be confirmed with regex. I wrote a pattern. Except one rule my pattern honors everything else. I am listing my regex pattern below

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

I am checking for a string say first or last name which needs to start with a alphabet and can have any one of (- or ! or ' or ` or spaces ) these 5 characters ONE AND ONLY IF there is a second word. If a name has 2 words with a space in between then its ok. some examples

List of Valid Names
TIMOTHY
JONATHON
PATRICK
B`ELLA
SUZY JANE - Only one space allowed
SUZY-JANE

List of Invalid Ones
T~ELLA - Because this ~ is not part of regex
SUZY - JANE - No space allowed between hyphens
SUZY  JANE - 2 spaces betweeb words not allowed
GRACO&LAME - & is not allowed

My regex passes all these above conditions But fails when the name ends in any one of the special character. For example, if I give JOHN- OR JOHN' OR JOHN! OR JOHN` OR JOHN (with s spaces at the end) these are not valid but my regex isnt able to handle it

Can some one tell me how to write a conditional regex? Like one and only if there is a second word then the regex pattern must allow the entry of these special characters.

like image 474
juniorbansal Avatar asked Oct 29 '25 05:10

juniorbansal


2 Answers

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.

like image 94
stema Avatar answered Oct 31 '25 08:10

stema


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)?
like image 28
Ingo Avatar answered Oct 31 '25 06:10

Ingo