Simon
Simon

Reputation: 609

.Net Reg Ex exact match

RegEx makes my head hurt, can anyone solve this for me?

In c# I'm calling the following and expecting true, I must admit I'm very week at regex.

Also a brief explanation on the implications of the impact of ( ) and the \ before the &.

var isValid = Regex.IsMatch(
     "from=20100101&to=20121231",
     "^(from=)([0-9]{6})\\&to=([0-9]{6})$"
);

Upvotes: 0

Views: 74

Answers (3)

Steve
Steve

Reputation: 216303

This will return true

var isValid = Regex.IsMatch("from=20100101&to=20121231",@"^from=[0-9]{8}&to=[0-9]{8}$");

The \ is used to escape an otherwise special character. So is treated at its literal value and not for its meaning in the Regular Expression Language. For example \. means match a point while a . by itself is a wildcard and means "Matches any single character except \n."

The (subexpression) is called grouping and captures everything matched with the inside subexpression and assigns it a zero-based ordinal number. This match could be referenced with the ordinal number assigned using this syntax \0
The argument is broad and has numerous variations.
You could start from this reference on MSDN

Note. I have corrected your pattern removing the grouping, the \& (ampersand is not a special char) and extending the number matching to 8 digits (if you have dates composed of only 6 digits then you could set {6,8} meaning min 6, max 8 digits)

Upvotes: 2

Mark Sherretta
Mark Sherretta

Reputation: 10230

You have asked for 6 consecutive digits with the {6}. However, you are really looking for 8, yyyymmdd.

Upvotes: 1

sQVe
sQVe

Reputation: 2015

Try this:

^from=(\d{8})&to=(\d{8})$

Upvotes: 3

Related Questions