user3290526
user3290526

Reputation: 139

Regular expressions exclusive or

I am trying to write a section of regular expression where it accepts either word characters or numbers, but not both (exclusive or).

Right now I have:

[\w\d]+

To represent a word that is made of either digits or letters/underscores. But that still lets things like 5x and 143243243243242323a pass through, because technically they are letters or numbers. I have tried things like [\w]+|[\d]+ but it has not worked for me so far. Any help?

Upvotes: 0

Views: 2658

Answers (3)

Marius Schulz
Marius Schulz

Reputation: 16440

Try this pattern: ^(?:[a-zA-Z]+|\d+)$


You were already on the right track with [\w]+|[\d]+. The problem was that the anchors ^ (matching at the beginning of the string) and $ (matching at the end of the string) were missing. They make sure that there's nothing before or after \w+ or \d+, thus ensuring the word only consists of either word characters or digits, but not a mixture of both (or any other character). Also, as Gergo pointed out, \w also matches digits.

The above pattern could also be written as the following, if that's clearer to you:

^[a-zA-Z]+$|^\d+$

Upvotes: 0

vinodh Barnabas
vinodh Barnabas

Reputation: 42

You can use [a-zA-Z_]+|[0-9]+

To add boundary, like start of string and end ^[a-zA-Z_]+$|^[0-9]+$

if you want grouping, use it as ([a-zA-Z_]+|[0-9]+)

For non-capturing group use (?:[a-zA-Z_]+|[0-9]+)

Upvotes: 0

Gergo Erdosi
Gergo Erdosi

Reputation: 42048

This regex matches the words you described:

/^(?:[a-z_]+|\d+)$/i

If you don't want to match the underscore, simply remove it:

/^(?:[a-z]+|\d+)$/i

Upvotes: 1

Related Questions