Simple Regex issue

  • Thread starter Thread starter CJ
  • Start date Start date
C

CJ

I'm not an expert on regular expressions, but I thought I knew how to
construct simple ones :-)

I have two very simple regular expresions:
"|1|(?<dt>\d\d-\d\d-\d\d\d\d).*" and ".*(?<dt>\d\d-\d\d-\d\d\d\d).*"
With the input string @"|1|01-08-2005 12:57:12", both regular
expressions match. But the named group dt is correct for the second
expression (01-08-2005) and just an empty string for the first, which
just doesn't make much sense to me.
 
I'm not an expert on regular expressions, but I thought I knew how to
construct simple ones :-)

I have two very simple regular expresions:
"|1|(?<dt>\d\d-\d\d-\d\d\d\d).*" and ".*(?<dt>\d\d-\d\d-\d\d\d\d).*"
With the input string @"|1|01-08-2005 12:57:12", both regular
expressions match. But the named group dt is correct for the second
expression (01-08-2005) and just an empty string for the first, which
just doesn't make much sense to me.

The | is a special character in a Regex... it means "this or that" (whatever
is before or after the | character.) So in this case, you are probably
matching the empty string before the first | in the first Regex. If you want
those characters to match explicitly, escape them:

\|1\|(?<dt>\d\d-\d\d-\d\d\d\d).*
 
I have two very simple regular expresions:
"|1|(?<dt>\d\d-\d\d-\d\d\d\d).*" and ".*(?<dt>\d\d-\d\d-\d\d\d\d).*"
With the input string @"|1|01-08-2005 12:57:12", both regular
expressions match. But the named group dt is correct for the second
expression (01-08-2005) and just an empty string for the first, which
just doesn't make much sense to me.
Your first expression uses the | operator, which is regex for "or". If
you escape it, it should work fine:

"\|1\|(?<dt>\d\d-\d\d-\d\d\d\d).*"

Greetings,
Wessel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top