Kaspar
Kaspar

Reputation: 103

Regex match optional character only if non-digit

I am trying to match string a on which the first character is 1-9 and the next three characters are 0-9. If there are any additional characters the first additional character cannot be a digit. The full string cannot contain a @ character.

Strings that should pass

Should not pass

I came up with ^[1-9][0-9]{3}(\D)? so far. But this passes 12345 as well.

Any help or guidance would be highly appreciated :)

Upvotes: 1

Views: 640

Answers (3)

suraj.tripathi
suraj.tripathi

Reputation: 467

Use this ^[1-9][0-9]{3}(?:$|[^@\d][^@]*)

console.log('1234'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('1234 5678910'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('1234AB 12345678'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('1234stackoverflow'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('1234 stackoverflow'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('0123'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('123'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('12345'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('1235@6789'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));
console.log('ABCDEF'.match(/^[1-9][0-9]{3}(?:$|[^@\d][^@]*)/));

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

Try this regex:

^[1-9][0-9]{3}([^@0-9][^@]*)?$

If I read your requirement correctly, matching strings should begin with 1-9, followed by 3 digits of any number, followed by anything provided it not be a number or at sign. The [^@0-9] in the regex is a negative character class, matching any character which is non numeric and not the at symbol.

Demo here:

Regex101

Upvotes: 2

baao
baao

Reputation: 73221

You can use this to get the correct matches:

/^[1-9]\d{3}[a-z]*$/i

Upvotes: 0

Related Questions