user1406737
user1406737

Reputation: 175

Combining 2 regexes, one with exact match using OR operator

I am trying to combine:

^[a-zA-Z.][a-zA-Z'\\- .]*$

with

(\W|^)first\sname(\W|$)

which should check for the exact phrase, first name, if that is correct. It should match either the first regex OR the second exact match. I tried this, but appears invalid:

^(([a-zA-Z.][a-zA-Z'\\- .]*$)|((\W|^)first\sname(\W|$))

This is in javascript btw.

Upvotes: 2

Views: 272

Answers (2)

d0nut
d0nut

Reputation: 2834

Combining regular expressions generally can be done simply in the following way:

Regex1 + Regex2 = (Regex1|Regex2)

^[a-zA-Z.][a-zA-Z'\\- .]*$
    + (\W|^)first\sname(\W|$) =
(^[a-zA-Z.][a-zA-Z'\\- .]*$|(\W|^)first\sname(\W|$))

Because some SO users have a hard time understand the math analogy, here's a full word explanation.

If you have a regex with content REGEX1 and a second regex with content REGEX2 and you want to combine them in the way that was described by OP in his question, a simple way to do this without optimization is the following.

(REGEX1|REGEX2)

Where you surround both regular expressions with parenthesis and divide the two with |.

Your regex would be the following:

(^[a-zA-Z.][a-zA-Z'\\- .]*$|(\W|^)first\sname(\W|$))

Your first regex has an error in it, though, that makes it invalid. Try this instead.

(^[a-zA-Z.][a-zA-Z'\- .]*$|(\W|^)first\sname(\W|$))

You had \\ in the second character class where you wanted \

Upvotes: 1

ndnenkov
ndnenkov

Reputation: 36110

The problem is that the first regex is messed up. You don't need to double escape characters. Therefore

\\- 

Will match an ascii character between \(92) and (32). Remove one of the slashes.

Reference

Upvotes: 0

Related Questions