1

I want to be able to split a formatting string on the variables' position indicators. It will chop out the curly braces and the position indicating numbers in between them.
So, the string:

string format = "{0} field needs to be set to '{1}' when {2},  Fixit.  NOW!";

Should resolve to 3 strings.

  • " field needs to be set to '"
  • "' when "
  • ", Fixit. NOW!"

We use string like the above 'format' to build error messages. My goal is to add generic unit tests that can take in the format and verify that an error message was generated that matches the expected format. Since both the error generation code and the unit test reference the same formatting, the unit tests won't need to be updated when minor changes are made to the message.

In the above example, i'll be able to test for the expected results, via a call to a new method called SplitFormatString.

string fieldName = "UserName";
string expectedValue = "Bob";
string condition = "excellence is a must";
string errorMessage = TestFieldValueErrorCase( );
AssertStringContainsAllThese(errorMessage, SplitFormatString(format), fieldName, expectedValue,condition);

With validation

public static void AssertStringContainsAllThese(string msg, string[] formatChunks, params string[] thingsToFind)
{
  foreach (var txt in formatChunks.Concat(thingsToFind))
  {
    Assert.IsTrue(msg.Contains(txt), "Could not find <<" + txt + ">> in msg >>> " + msg);               
  }
}

I'd rather use regex than an inelegant approach using substrings.

2
  • 2
    Like this? and then just split on \n? Commented May 25, 2017 at 17:28
  • Yes, like that. Thx Commented May 25, 2017 at 18:50

1 Answer 1

5

I think you will want Regex.Split

Splits an input string into an array of substrings at the positions defined by a regular expression pattern.

Regex.Split("{0} field needs to be set to '{1}' when {2},  Fixit.  NOW!", @"{\d+}");

Should output:

["","field needs to be set to '","' when ",",  Fixit.  NOW!"]
Sign up to request clarification or add additional context in comments.

1 Comment

Sure .Where(s => !string.isNullOrWhitespace(s)).

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.