s_k_t
s_k_t

Reputation: 739

Matching Special character '-' using Regular expression in Javascript

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

Answers (4)

Fabricator
Fabricator

Reputation: 12782

  • Use -? to indicate - may appear no more than once
  • [/-] does not make sense

This should work:

^(P|p)[0-9]{4}(ABC|abc)[0-9]{4}-?$

Upvotes: 0

bloodyKnuckles
bloodyKnuckles

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

Fantini
Fantini

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

georg
georg

Reputation: 215049

Some problems here:

  • regexes are not strings, use /.../, not '...'
  • instead of (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

Related Questions