开发者

Regular Expression to match sequences of one or more letters except for a specific value

开发者 https://www.devze.com 2022-12-30 00:57 出处:网络
Looking for some help with a Regular Expression to do the following: Must be Alpha Char Must be at least 1 Char

Looking for some help with a Regular Expression to do the following:

  • Must be Alpha Char
  • Must be at least 1 Char
  • Must NOT be a specific value, e.g. != "Default"

Thanks for开发者_如何学Python any help, Dave


Use a negative lookahead:

^(?!Default)[a-zA-Z]+$


Solve this in two steps:

  1. compare against the regular expression [a-zA-Z]+ which means "one or more of the letters from a-z or A-Z
  2. if it passes that test, look it up in a list of specific values you are guarding against.

There's no point in trying to cram these two tests into a single complex regular expression that you don't understand. A good rule of thumb with regular expressions is, if you have to ask someone how to do it, you should strive to use the least complex solution possible. If you don't understand the regular expression you won't be able to maintain the code over time.

In pseudocode:

if regexp_matches('[a-zA-Z]+', string) && string not in ['Default', 'Foobar', ...] {
    print "it's a keeper!"
}
0

精彩评论

暂无评论...
验证码 换一张
取 消