user1512559
user1512559

Reputation:

Regular expression issue when validating '/' character

I have been having some problems with regular expressions. I want to validate user input when a bus number is entered.

Examples: 37, 37A, 37S, 37A/L, 16A/250, 16A/250K etc

The regular expression I came up with is

(^\d{1,3}[A-Z]{0,3})|(^[\d{1,3}[A-Z]{0,3}\/\d{0,3}[A-Z]{0,3}])

It validates 37, 37A, 37S but when it comes to validating 37A/L it fails. Can someone tell me where I am going wrong with this?

Note:I am using a regular expression validator for a text box. I have placed this in the ValidationExpression.

Upvotes: 4

Views: 210

Answers (3)

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

You do not need to escape the / character, try the following:

(^\d{1,3}[A-Z]{0,3}(?:/\d{0,3}[A-Z]{0,3})?)

You can additionally enforce that the entire line matches the regex by specifying the EOS character:

(^\d{1,3}[A-Z]{0,3}(?:/\d{0,3}[A-Z]{0,3})?$)

NB as @MaxwellTroyMiltonKing points out in the comments the parenthesis around the entire regex are unnecessary:

^\d{1,3}[A-Z]{0,3}(?:/\d{0,3}[A-Z]{0,3})?$

Upvotes: 2

Seimen
Seimen

Reputation: 7250

Try this:

^(\d{1,3}[A-Z]{0,3})(\/\d{0,3}[A-Z]{0,3})?$

Upvotes: 0

A Coder
A Coder

Reputation: 3056

It was having problem as end of string was not specified.

Replace with this,

(^\d{1,3}[A-Z]{0,3}$)|(^\d{1,3}[A-Z]{0,3}\/\d{0,3}[A-Z]{0,3}$)

Hope this helps.

Upvotes: 2

Related Questions