Reputation: 739
I have a string p9909abc0221-
and p9909abc0221
I have written regular expression to match the user input and validating it .The String may or may not contain '-' spcial character in last .
Using the below code
return (str !== undefined && str.match('^(P|p)[0-9]{4}(ABC|abc)[0-9]{4}[/-]$'));
I think I am doing wrong for '-' special character . Any help would be great
Upvotes: 0
Views: 4907
Reputation: 12782
-?
to indicate -
may appear no more than once[/-]
does not make senseThis should work:
^(P|p)[0-9]{4}(ABC|abc)[0-9]{4}-?$
Upvotes: 0
Reputation: 12089
Based on the two examples you provided, this works for me:
str.match(/p\d{4}abc\d{4}-?/i)
Updated, based on comment below.
Upvotes: 0
Reputation: 2077
If the '-' char may or may not be contained you need to use '?'
So your regex needs to be like this:
^(P|p)[0-9]{4}(ABC|abc)[0-9]{4}-?$
You can try regex on: http://regex101.com/r/cU5oK8
Upvotes: 0
Reputation: 215049
Some problems here:
/.../
, not '...'
(ABC|abc)
just make the pattern case-insensitive (unless you want to disallow Abc
)[\-]
is just the same as -
\d
is a shortcut for [0-9]
That is,
return (str !== undefined && str.match(/^p\d{4}abc\d{4}-?$/i));
or
return (str !== undefined && str.match(/^[Pp]\d{4}(ABC|abc)\d{4}-?$/));
Upvotes: 1