Home > Blockchain >  Regex - do not start with characters [SG|sg]
Regex - do not start with characters [SG|sg]

Time:02-16

What is the proper regex for negating anything that starts with sg-.* or SG-.*.

I want the validation to not accept the following.

sg-WebServers_001
SG-WebServers_001

But anything else should be fine. Example:

The following are accepted.

mq-WebServers_001
MQ-WebServers_001

I tried [^-sg|SG].* but it accepts sg-WebServers_001 and SG-WebServers_001

CodePudding user response:

Your regular expression library must have support for “negative lookahead”.

Something like ^(?!(SG|sg)-). $ will match anything not beginning with “SG-” or “sg-”.

CodePudding user response:

You can use a look behind to make sure your string does not starts with it.

(?<!^)[^sS][^gG]-

CodePudding user response:

You can use a negative match anchored to the start of your pattern to match everything but ...

^(?![sS][gG]-)..-.*

If you don't want to prevent the patterns sG or Sg, you would instead use this pattern:

^(?!sg|SG-)..-.*

This pattern will correctly match everything that

  1. Does not start with s or S followed by g or G followed by a dash
  2. Contains two characters followed by a dash
  3. And then whatever for the rest of the string

(thanks to @Dúthomhas for spotting the missing dash)

Test code:

string[] input =
{
    "sg-WebServers_001",
    "SG-WebServers_001",
    "mq-WebServers_001",
    "MQ-WebServers_001"
};

string pattern = "^(?![sS][gG])..-.*";

foreach (string s in input)
    if (Regex.IsMatch(s, pattern))
        Console.WriteLine(s);

output:

mq-WebServers_001
MQ-WebServers_001
  • Related