Below is my regex:
[^4\\d{3}-?\\d{4}-?\\d{4}-?\\d{4}$]
But it throws an error at -
. I am using ?
, which should al
Try escaping -
with \
and remove [
and ]
:
^4\d{3}\-?\d{4}\-?\d{4}\-?\d{4}$
The problem with the regex is that the pattern is enclosed with [
and ]
that are treated as character class markers (see Character Classes or Character Sets):
With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an
a
or ane
, use[ae]
.
In character classes, -
creates ranges between literal characters. In your case, these ranges are not valid (go from a character with higher values to those with lower values) since the {4}
and other subpatterns were treated as separate characters, not special constructs:
So, all you need to do is remove the [
and ]
on both sides:
^4\d{3}-?\d{4}-?\d{4}-?\d{4}$
See regex demo.