Lill Lansey
Lill Lansey

Reputation: 4915

Regular expression - what is my mistake?

I would like to match either any sequence or digits, or the literal: na . I am using:

"^\d*|na$"

Numbers are being matched, but not na.

Whats my mistake?

More info: im using this in a regular expression validator for a textbox in aspnet c#.

A blank entry is ok.

Upvotes: 1

Views: 226

Answers (4)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297265

Perhaps ^(?:\d*|na)$ would be better. What language/engine? Also, please show the input and, if possible, the snippet of the code.

Also, it is possible that you aren't matching "na" because there is a new line after it. The digits wouldn't be affected because you did not specify a $ anchor for them.

So, depending on the language and how the input is acquired, there might be new-line between "na" and the end of the string, and $ won't match it unless you turn on multi-line match (or strip the string of the new line).

Upvotes: 1

Chris Tonkinson
Chris Tonkinson

Reputation: 14469

It's because the expression is being read (assuming PCRE):

"^\d*" OR "na$"

Some parentheses would take care of that in a jiff. Choose from (depending on your needs):

"^(\d+|na)$"    // this will capture the number or na
"^(?:\d+|na)$"  // this one won't capture

Cheers!

Upvotes: 9

Gumbo
Gumbo

Reputation: 655519

The | operator have a higher precedence than the anchors ^ and $. So the expression ^\d*|na$ means match ^\d* or na$. So try this:

^(\d*|na)$

Or:

^\d*$|^na$

Upvotes: 6

Max Schmeling
Max Schmeling

Reputation: 12509

This may not be the best or most elegant way to fix it, but try this:

"^\d*|[n][a]$"

Upvotes: -2

Related Questions