Reputation: 1633
I'm using openXML and I'm trying to loop through an excel file to see if anything matches with a specific pattern. My Regex pattern is as fallows @"(?<!\w)#\w+"
. This should return anything that starts with a "#
". There are a number of defined names that begin with "#
" such as <definedName name="_KEY" hidden="1" localSheetId="3">#REF!</definedName>
in my excel workbook xml. However my count is returning zero when I try and find the defined name.
My code is as fallows
First I browse for the file and select the file. I've made sure that this works perfectly.
I then try and do a count and loop through each match and it's here where I have my issue. I assume I'm messing up my foreach
loop and I really need some guidance.
var spreadsheet = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(filePath, false);
var workbook = spreadsheet.WorkbookPart;
var names = workbook.Workbook.DefinedNames;
//result.InactiveNamedRangeCount = names.Where(n => n.InnerText.Contains(pattern)).Count();
foreach (Match match in Regex.Matches(names.ToString(), @"(?<!\w)#\w+"))
{
result.InactiveNamedRangeCount = names.Where(n => n.InnerText.Contains(match.ToString())).Count();
}
Upvotes: 0
Views: 348
Reputation: 2105
Check what is returned by names.ToString(), you shouldn't run regex on it.
To get the number of DefinedNames matching your pattern, you can use:
names.Count(n => Regex.IsMatch(n.InnerText, @"(?<!\w)#\w+"));
Upvotes: 1