tags:

views:

131

answers:

3

Hi,

I'm banging my head against a wall with a regular expression. I'm trying to define an expression that excludes exactly this text 'System' (case insensitive), but can contain the word 'System' providing it's not just that.

Examples:

  • System == INVALID
  • SYSTEM == INVALID
  • system == INVALID
  • syStEm == INVALID
  • asd SysTem == Valid
  • asd System asd == Valid
  • System asd == Valid
  • asd System == Valid
  • asd == Valid
+1  A: 

Try this:

^(?!system$)

Or this to match the whole line:

^(?!system$).*$

The regex has a negative look-ahead on its beginning, which doesn't match if "system" is the entire string.

Kobi
Just out of curiosity, how does the ?! operator work? I've never used that one (though I've used pretty much regex I tend to find solutions which don't use 'not').
Alxandr
Ahh, so simple! I'm sure I tried that...! Thankyou.
Kieron
@Alxandr - it checks what follows your current position. For example, `c(?!4)` will match c from `Doc12`, but not the c on `Doc42`. A look-around doesn't capture, so I don't have to worry about replacing the digit, or check edge case (for example, if c were the last character: `Doc`).
Kobi
+4  A: 

Reject if it matches ^system$ (make sure i flag is ON).

Amarghosh
This should be the first option, or course. I naturally (and possibly wrongly) assumed the OP cannot do it.
Kobi
+1  A: 
^$|^.{1-5}$|.{7}|^[^s]|^.[^y]|^..[^s]|^...[^t]|[^e].$|[^m]$ 

But use amarghosh's answer if you can.

(updated as per suggestion below)

Steve Bennett
You probably meant `.{1,5}`.
Kobi
heh, I wrote that without testing it. I'm kind of shocked that it actually worked first try. The first two clauses are redundant though, so: (^.{1-6}$)|(.{8})|(^[^s])|(^.[^y])|(^..[^s])|(^...[^t])|([^e].$)|([^m]$)Nice tip about ?! though - I hadn't heard of it.
Steve Bennett
oops. that regex lets through "systuem". (and fails on empty string, which is apparently acceptable?)try:^$|^.{1-5}$|.{7}|^[^s]|^.[^y]|^..[^s]|^...[^t]|[^e].$|[^m]$
Steve Bennett
Steve - Welcome to stack overflow. It is best to update your answer than to add another one as a comment. Also, start the regex line with 4 spaces - it will format it as code.
Kobi