Re: Regex Usage, or use Substring?

Tech-Archive recommends: Speed Up your PC by fixing your registry



jp2msft <jp2msft@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
Two part question:

1. Is Regex more efficient than manually comparing values using Substring?

Sometimes.

2. I've never created a Regex expression. How would I use regex to do the
equivalent of what I have coded using Substrings below?

Well, let's start off by getting rid of the unnecessary substrings,
when you're only looking at a single character:

string s = TextBox1.Text.ToUpper();
char ch = s[0]; // read first character [B,C,X]
ok = false; // Only one path can produce ok = true
if (ch=='B' || ch=='C' || ch=='X')
{
ch = s[1]; // read second character [P,0,5,7]
if (ch == 'P' || ch == '0' || ch == '5' || ch == '7'))
{
if (len > 12) // Reversed if (12 < len) for readability
{
if (s[7] == ' ' && s[12] == ' ')
{
if (len == 15)
{
ok = IsNumeric(new string[] { s.Substring(2, 5),
s.Substring(8, 4),
s.Substring(13, 2) });
}
else
{
// This message looks incorrect - we've just checked
// the length, not the data
Console.WriteLine
("Non-numeric data found in numeric section");
}
}
else
{
Console.WriteLine
("There should be blanks at positions 8 and 13.");
}
}
}
else
{
Console.WriteLine("Second letter should be [P, 0, 5, or 7].");
}
}
else
{
Console.WriteLine("First letter should be [B, C, or X].");
}

Okay, now assuming that the IsNumeric call is actually to check whether
all of those characters are digits, we could indeed convert all of this
into a regular expression - but it would either match or not. It
wouldn't say which part failed. The regex would be something like:

@"^[BCH][P057]\d\d\d\d\d \d\d\d\d \d\d$"

I haven't tested it, but it looks okay to inspection...

--
Jon Skeet - <skeet@xxxxxxxxx>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
.



Relevant Pages

  • Re: Force POSIX NFA in Perl?
    ... It could be done by putting something like '$' at the end of a regex. ... my $suffix = qr//; ... local our @substrings; ...
    (comp.lang.perl.misc)
  • Regex
    ... I am trying to form a regex to search my string and give me substrings ... split the string at every occurence of hyphen - character but not if a ...
    (microsoft.public.dotnet.languages.csharp)