Mike Fielden
Mike Fielden

Reputation: 10153

Javascript Regex match no spaces

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?

Upvotes: 1

Views: 1244

Answers (3)

Bobby
Bobby

Reputation: 18315

Require at least one digit after PC

/^PC\d+/

or require the String to last the entire line

/^PC\d*$/

Upvotes: 2

jfriend00
jfriend00

Reputation: 708036

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

Upvotes: 6

Pointy
Pointy

Reputation: 413996

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.

Upvotes: 2

Related Questions