jonas
jonas

Reputation: 1652

Regular expression to exclude number from list

I would like to use regex pattern with <input> form element.

In this pattern I would like to put a range of numbers that is not allowed as input.

For instance I would have a list of number {1,4,10} and allowed input is any number except these.

I've managed to create this regex:

[^(1|4|10)]

But that also excludes everything contain 0,1 or 4 such as 10.

Upvotes: 0

Views: 632

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

If negative lookaheads be allowed, then you can try the following regex:

^(?!(?:1|4|10)$)\d+$

Regex101

Upvotes: 2

ATJ
ATJ

Reputation: 325

You don't need to use a character class here (i.e. the [ ]), because the | already means 'this character or that character'. Instead, use:

    ^(1|4|10)$

The ^ matches the start of a string, and the $ matches the end of the string, so this will only match 1 (with nothing else), 4 (with nothing else) or 10 (with nothing else).

By the way, to test regex, you can use a online tester such as https://regex101.com/.

Upvotes: 0

Related Questions