1

I am trying to match the following string in Javascript Regex

PC123456

This is what I have:

/^PC\d*/

This works for every instance minus one with a space after the "PC" which does work but it should fail. Example:

PC 123456

That should fail. What do I need to add to make the second condition fail?

3 Answers 3

6

Change your regex to this:

/^PC\d+$/

This requires at least one digit and only matches if there is nothing else in the string except the PC and the digits.

This will match:

PC123456
PC1
PC99

It will not match:

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

Comments

2

You need to add an end-of-source anchor:

/^PC\d*$/

The "$" at the end insists that the pattern match the entire string. Without it, "PC" with no immediately subsequent digits matches because "*" means "zero or more", not "one or more".

You could alternatively change the "*" to a "+", but I don't know whether "PC" by itself is valid in your application.

Comments

2

Require at least one digit after PC

/^PC\d+/

or require the String to last the entire line

/^PC\d*$/

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.