I’m working with an array of strings, and would like to do the following:
//Regex regex; List<string> strList; List<string> strList2;
foreach (string str in strList){
if (regex.IsMatch(str)) { //only need in new array if matches...
strList2.Add(regex.Replace(str, myMatchEvaluator))
//but still have to apply transformation
}
}
Now, I know that works, but that effectively means running the same regex twice on each string in the array. Is there a way to collapse both of these steps – the filtering and the transformation – into one regex-parsing call?
(One that would work most of the time is
string str2 = regex.Replace(str, myMatchEvaluator);
if (str2 == str)
strList2.Add(str2);
But that would often throw out some valid matches that still didn’t need replacement.)
EDIT: A regex example, roughly similar to mine, to illustrate why this is tricky:
Imagine looking for words at the beginning of lines in a log file, and wanting to capitalize them.
The regex would be new Regex("^[a-z]+", RegexOptions.IgnorePatternWhiteSpace), and the replacement function would be match => match.ToUpper().
Now some first words are already capitalized, and I don’t want to throw them away. On the other hand, I don’t want to upper-case all instances of the word on the line, just the first one.
Building off of all of the answers I’ve received, the following works: