3

I am looking to validate an input text against the following pattern in JS/JQuery: P-1-A100 or

R-5-M42 or P-10-B99, etc

The text essentially needs to have the following six parts:

  1. Single character P or R followed by

  2. A single '-' followed by

  3. Any number with 1 or more digits followed by
  4. A single '-' followed by
  5. Any alphabet (A-Z) followed by
  6. Any number with 1 or more digits.

Do I need to take care of escape characters as well. How do I make sure that the input text matches the regular expression.

If it does match, how can I extract the last part (Number)from the input text. I have tried this, but isn't working for me

var isMatch = inputText.match([PR]-\d+-[A-Z]+\d+)

3
  • 3
    Perhaps, /^[PR]-\d+-[A-Z]+(\d+)$/? Use a capturing group around the subpattern that your are interested in getting from the text. Commented Jun 14, 2016 at 9:36
  • 1
    See jsfiddle.net/t1g566a0 Commented Jun 14, 2016 at 9:48
  • That worked like a charm!Thanks Wiktor! Commented Jun 14, 2016 at 10:02

1 Answer 1

1

You just need to add group to your regex.

var match = inputText.match(/^[PR]-\d+-[A-Z]+(\d+)$/);

If match is not null, then number will be in array on position match[1].

var number = match ? match[1] : null;

EDIT: Added anchors as Aaron suggested.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.