Re: Regex Usage, or use Substring?
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Wed, 25 Jun 2008 21:38:29 +0100
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
.
- Follow-Ups:
- Re: Regex Usage, or use Substring?
- From: Mythran
- Re: Regex Usage, or use Substring?
- References:
- Regex Usage, or use Substring?
- From: jp2msft
- Regex Usage, or use Substring?
- Prev by Date: Re: List
- Next by Date: Re: Windows Services - FileWatcher
- Previous by thread: Regex Usage, or use Substring?
- Next by thread: Re: Regex Usage, or use Substring?
- Index(es):
Relevant Pages
|