tags:

views:

210

answers:

7

Hello,

I need a regular expression that will not let someone continue to check out if the type in the word 'box' or 'Box' or 'BOX' followed by numbers. Both conditions have to be met for this to work, the word box and the numbers not one or the other. Does anyone know how to write this?

EDIT:

Hey guys, I've tried a few and the problem is that it's preventing regular addresses like 1234 S. Something Lane. All I want to prevent is if the user types in something like p.o. box 1234. We're figuring anything with the word 'box' and numbers after it should not be accepted.

thanks

+6  A: 

Edited after the question was clarified:

new Regex(@"\bbox\s*\d+", RegexOptions.IgnoreCase);

That will match "box" as a word by itself, optionally followed by whitespace, followed by a number, anywhere in the input string. So it will match:

  • box12
  • Box 12
  • P.O. Box 12
  • BOX 12a

It won't match:

  • boxtree 12
  • boombox 12
  • Box Pog
  • Box Pog 12

(It would have been very helpful if your original question had explained what you were actually trying to do!)

RichieHindle
+5  A: 
(box|Box|BOX)[0-9]+

EDIT after clarification of question:

I guess you actually want a case-insensitive search on:

box\s*\d+
  • \s*: Any amount of whitespace
  • \d+: At least one number

You can define the number of digits, if you want to. Example for 3-5 digits:

box\s*\d{3,5}
soulmerge
A: 

At least in my experience it's easier to write a RegEx to match the expected case strictly, rather than trying to exclude an exceptional case.

TheMissingLINQ
A: 

If you show an example of the format you're wanting to accept it will be easier for people to answer this.

If you're wanting to prefix a string with any variant of "Box" and then with numbers, something like this should work (make sure you use RegexOptions.IgnoreCase)

^box\d+$

Which would match for ...

box1
BOX1234567
bOx3
...etc...
Hugoware
A: 

have you tried something like

/box\d+/

plus IgnoreCase?

Jason
A: 

this :

box|Box|BOX\d+

will match these specific cases box,Box,BOX and all these followed by numbers but it will also return true in this case for instance :

asBox123asdasd

If you want to get true if the string is exactly box123 for instance you should use :

^box|Box|BOX\d+$

instead

Savvas Dalkitsis
\d* means that \d can be matched 0 or more times and the OP requires there to be at least one number.. use \d+ instead.
DeadHead
oh i knew that. i misread the question...
Savvas Dalkitsis
A: 

Don't forget the "post office" option.

^(p(ost|.) *o(ffice|.) )?box *[0-9]+$

Jay