2

I have an input string that's generated as in following example:

string.Format("Document {0}, was saved by {1} on {2}. The process was completed 
{3} milliseconds and data was received.", 
"Document.docx", "John", "1/1/2011", 45);

It generates string looks like this then:

Document Document.docx, was saved by John on 1/1/2011. The process was completed 
45 milliseconds and data was received.

Once such a string is received from a different application, what would be the easiest way to parse with regex and extract the values Document.docx, John, 1/1/2011, 45 from it.

I am looking for the easiest way to do this as we will have to parse a number of different input strings.

1 Answer 1

9

You could use something like this:

private static readonly Regex pattern =
    new Regex("^Document (?<document>.*?), was saved by (?<user>.*?) on " +
        "(?<date>.*?)\\. The process was completed (?<duration>.*?) " +
        "milliseconds and data was received\\.$");

public static bool MatchPattern(
    string input,
    out string document,
    out string user,
    out string date,
    out string duration)
{
    document = user = date = duration = null;

    var m = pattern.Match(input);
    if (!m.Success)
        return false;

    document = m.Groups["document"].Value;
    user = m.Groups["user"].Value;
    date = m.Groups["date"].Value;
    duration = m.Groups["duration"].Value;

    return true;
}

It might be worth refactoring to return a composite type that contains all of the information you want instead of using out parameters. But this approach should still work.

To use this code, you would do something like this:

var input = "...";

string document, user, date, duration;
if (MatchPattern(input, out document, out user, out date, out duration)) {
    // Match was successful.
}
Sign up to request clarification or add additional context in comments.

2 Comments

awesome, you save my day :-)
trying to find python equivalent :/

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.