Match string that contain unknown text

Viewed 282

I have a web service that I'm calling that returns a list of error messages. I'm then doing a foreach over this list, and matching based on the text of the error messages in a config file. However, some of the error messages returned from the web service contains some unknown data, such as a date, or a number.

How can I match this text, using C#? Would I have to split the string and try to match each individual word? How do I deal with an unknown variable such as a date or number when doing a ".Contains(...)"?

Here's an example:

Web service list might contain the following

"This is an example static error message"
"Another example static error message"
"This is an error message for employee 2"
"This is an error message dated 11/2/2017"
"Employee 3 does not work here anymore"

In my config file, I have the following:

<add errorText="This is an example static error message" field="N/A" />
<add errorText="Another example static error message" field="N/A" />
<add errorText="This is another example for employee **X**" field="N/A" />
<add errorText="This is an error message dated **X**" field="N/A" />
<add errorText="Employee **X** does not work here anymore" field="N/A" />
3 Answers

You can use Regex to match them:

Regex.IsMatch(message, "This is another example for employee .+")
Regex.IsMatch(message, "This is an error message dated .+")

From your config files, you could build regular expressions as follows:

String configString = GetConfigString(3); // "This is another example for employee **X**"
String regexPattern = String.Concat("^", configString.Replace("**X**", ".+"), "$");

Boolean match = Regex.IsMatch("This is another example for employee John", regexPattern);

and then use such regex to match your text strings.

You could also build all of your regular expression patterns as soon as your application starts and cache them somewhere for future use:

String configStrings = GetConfigStrings();
String[] regexPatterns = new String[configStrings.Length];

for (Int32 i = 0; i < configStrings.Length; ++i)
    regexPatterns[i] = String.Concat("^", configStrings[i].Replace("**X**", ".+"), "$");

Since you have a mixed type of possible string replacement within your framework, sticking to the .+ token is the better choice.

If course, it's up to you to eventually build a configuration file parsers and implement GetConfigString and GetConfigStrings methods (or only one, depending on the approach you want to use).

If you don't like to take regex approach, like me, you can add the known error messages into a HashSet and keep them in memory and then lookup which error message matches the most with the error message on hand, like a match score.

Related