Search STring in Regular Expression

  • Thread starter Thread starter tshad
  • Start date Start date
T

tshad

I am trying to search a string that can have 3 values and want to use
regular expressions.

I tried:

string s = "SKT123";

if (Regex.IsMatch(s, @"SKT|SKT_L1|SKECT"))
s = s;
else
s = s;

This was a match.

but

string s = "SKE";

if (Regex.IsMatch(s, @"SKT|SKT_L1|SKECT"))
s = s;
else
s = s;

was not a match.

I am trying to get an exact match where it is equal to SKT or SKT_L1 or
SKECT.

How would I change this to get that result?

Thanks,

Tom
 
I am trying to get an exact match where it is equal to SKT or SKT_L1 or

Try:
Regex.IsMatch(s, @"^(SKT|SKT_L1|SKECT)$")

...where
^ means match must occur at the beginning of the string
$ means match must occur at the end of the string

(Note, the meaning of these is different if the multiline option is
set)

HTH
Kind regards,
Eliott
 
Hi,
"SKE" is not one of SKT or SKT_L1 or SKECT. It is contained within
"SKETC", but is not the same as. If you wanted to be able to make anything
starting with "SK", you could do

Regex.IsMatch(s, @"SK*"))

if the "CT" from "SKCT" is optional,

Regex.IsMatch(s, @"SKT|SKT_L1|SKE(CT)?"))

The exact expression to use really depends on EXACTLY what you want to match.

Ethan
 
"SKE" is not one of SKT or SKT_L1 or SKECT. It is contained within
"SKETC", but is not the same as. If you wanted to be able to make anything
starting with "SK", you could do

Regex.IsMatch(s, @"SK*"))

NO! The regex you have above would match "S" and then zero or more instances
of "K" ANYWHERE in the string, not just at the beginning, so "ABCS",
"ABCSK", "S", "123S456", and "SKKKKKABC" are all matches. Looks like you've
got your head in the DOS wildcard world, not the regex world.

"Anything starting with 'SK'" as you stated above would require "^SK" as the
regex.
 
Oops. Sorry about that. Jeff is correct.

Regex.IsMatch(s, @"SK.*")) would match everything from "SK" to the end of
the line (unless you use the multiline option).
Regex.IsMatch(s, @"SK\S*")) would match "SK" and all following characters up
to the next Space.
Regex.IsMatch(s, @"SK")) would match "SK" if it existed, but nothing after
that.

I think that is correct this time.
Ethan
 
Back
Top