Craig Gallagher Craig Gallagher - 9 months ago 43
C# Question

Regex looping through a foreach to find a certain pattern

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

. 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
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();


Answer Source

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+"));