0

I have a RegEx Patern like

    string _pattern = @"\d{4}-\d{2}\/\d{2}\/\d{4}";

How do I check if a string value belongs to this pattern in full or is part of this pattern.

for e.g if i send

        string someString= "0007-08/02/2012";
        Match m = Regex.Match(someString, _pattern);
        //i get a full match

but if i send

        string someString="0007-"
        //how do i check if this string value matches that pattern and is a substring.

Is there any other way of doing it ,other than using regex.

Thanks, csk

1
  • 1
    Your second example does not match the pattern. Commented Oct 10, 2012 at 10:52

3 Answers 3

1

If you want to match any substring of your pattern you has to add '?' in all of the optionals, something like this:

string _pattern = @"(\d{4})?(-)?(\d{2})?(\/)?(\d{2})?(\/)?(\d{4})?";

This pattern will match any substring of you original pattern.

i.e.: 
0007-08/02/2012
0007-
08/02/2012
08/
/02/2012

All of that matches the pattern.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, you're right ( ) arround expression are missing in my answer, i'll edit it.
This allows for many other matches though. Things like "-/21/" or "2345-/" would match here.
Cool ! I tried it with '?' and the braces '()' separately.Your solution works.Thanks.
@LTAcosta to avoid those kind of matches I grouped them as desired like @"(\d{4}-)?(\d{2}\/\d{2}\/\d{4})?" separating the date part from the first 5 characters.
Yeah, that is what I was going to suggest, but I was unsure of your requirements. I wasn't sure which parts of your string would always occur, and which would only occur sometimes. Like that won't work properly for just 4 digits, since the 4 digits are tied to the -. If you needed to support both cases, you can | all the possible scenarios, or you can probably use an alteration construct.
0
string _pattern = @"\d{4}-(\d{2}\/\d{2}\/\d{4})?"

Comments

0

My suggestion is to postfix someString with a string known to match the pattern and test it:

string good = "0007-08/02/2012";
bool isMatch = Regex.Match(someString + good.Substring(someString.Length), _pattern)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.