C#正则expression式 – 从Excel公式中获取具有R1C1引用的行数据
我正在尝试使用正则expression式在Excel中获取行的引用。 例如,我有一个公式:
=SUM(R[-3]C[-1];R[-3]C;R[-3]C[2];R[-1]C[2]:R[1]C[3];RC[-1])
我只需要得到数字-3
, -3
, -3
, -1
目前,我正在使用正则expression式模式:
=?(R\[[-0-9]*\]|RC)
它给了我:
但是只有数字才是必要的。 而且,而不是RC
我必须得到0
。
提前致谢!
你非常接近 – 如果你在你的正则expression式中添加另一个捕获组,那么你可以从R[x]
取出R[x]
。 所以你的正则expression式是:
=?(R\[([-0-9]*)\]|RC)
注意这是你的正则expression式,在[-0-9]*
附近加上括号。
示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string formula = "=SUM(R[-3]C[-1];R[-3]C;R[-3]C[2];R[-1]C[2]:R[1]C[3];RC[-1])"; string pattern = @"=?(R\[([-0-9]*)\]|RC)"; System.Text.RegularExpressions.Regex parser = new System.Text.RegularExpressions.Regex(pattern); System.Text.RegularExpressions.MatchCollection matches; // parse formula matches = parser.Matches(formula); // iterate results foreach (System.Text.RegularExpressions.Match match in matches) { if (match.Groups[0].Value == "RC") { Console.WriteLine("0"); } else { Console.WriteLine(match.Groups[2].Value); } } Console.ReadKey(); } } }
我无法testing它,但可以使用类似下面的方法获取公式中引用的所有行:
Range formulaCell = worksheet.Range("A1"); Range referencedRange = formulaCell.DirectPrecedents; foreach(Range area in referencedRange.Areas) foreach(Range cell in area.Cells) Debug.Print((cell.Row - formulaCell.Row).ToString); // -3, -3, -3, -1, 0, 1, 0