首页 > 解决方案 > 正则表达式匹配空单元格

问题描述

我尝试在我的函数中使用正则表达式。它允许在正则表达式中找到具有指定字符串的单元格(忽略大小写)。

问题是,如果我在单元格之前有空框,我有一个例外。我不明白为什么 NULL 单元格是个问题。

我的功能:

public int FindSearchableCol()
{
    var j = 1;
    var x = FindMainInfoStartRow();
    var i = x;
    string test = ws.Cells[i, j].Value2;
    Regex searchable = new Regex(@"(?<=\*)(searchable)(?=\*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    try
    {
        while (true)
        {
            MatchCollection matches = searchable.Matches(ws.Cells[i, j].Value2);
            if (matches.Count > 0)
            {
                return j;
            }
            else
            {
                i++;
                if (ws.Cells[i, j].Value2 == "*MAIN INFO END*")
                {
                    i = x;
                    j++;
                }
            }
        }
    }
    finally
    {
    }
}

标签: c#excelinterop

解决方案


利用 :

MatchCollection matches = searchable.Matches(ws.Cells[i, j].Value2 ?? string.Empty)

反而 :

MatchCollection matches = searchable.Matches(ws.Cells[i, j].Value2)


推荐阅读