The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Mar 2010»»
SMTWTFS
  12
3
456
7
8
9
10
111213
1415161718
19
20
21222324252627
28293031

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Regular Expressions: "Does not start with...."

posted Wednesday, 1 November 2006
 

A coworker recently asked me how to have a regular expression check if something does not start with a certain value. For example, how to tell if an input value does not start with 'abc'.

Note that it's very easy to see if something does start with a certain value, just use the anchor-to-first-start char '^'. For example, this regex will check for all strings that start with 'abc' (followed by any \w character(s)):

    ^abc\w+

To see that something does not start with a given value, use the Grouping Construct 'Zero-width negative lookahead assertion":

    ^(?!abc)\w+

This would handle the following cases:

Pass - none of these start with 'abc': Fail - all of these start with 'abc':
defg
ab
xyz
11999
abc
abcdef

Note that there are four similar grouping constructs based on the combos of Positive/Negative - Lookahead/Lookbehind

  • Positive Lookahead
  • Negative Lookahead
  • Positive Lookbehind
  • Negative Lookbehind

You can download a free regex editor from MVP Roy Osherove

tags:  

links: digg this    technorati