tags:

views:

56

answers:

3

So I'm trying to write a regex and get it to match the string ONLY if the string doesn't start with the string 'username'

I tried something like ^([^username])... but that matches strings where the string doesn't start with any of those letters.

Any help would be appreciated!

+6  A: 
^(?!username)

using a negative lookahead.

The other option, depending on what your doing, would be to simply invert your logic. For instance, if you were doing

if foo matches <regex>

then just do

if !(foo matches <regex>)
Amber
perfect thanks amber.
onassar
+1  A: 

but that matches strings where the string doesn't start with any of those letters.

That's because square brackets ([]) denote a character class and the caret (^) negates the character class.

That being said, why do you have to use regex? This can be done with simple string matching, which is generally faster than regex. If there is a match check and see if the position is not the beginning of the string. You didn't specify a language, but most of them support this.

NullUserException
+2  A: 

In case you're using Perl: you can use the negative binding operator:

if($text !~ /^username/) {
    # do something
}
polemon