2016-10-04 13 views
1

正規表現を使用してExcelで行の参照を取得しようとしています。例えば、私は式:C#正規表現 - R1C1参照で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-11、現在0

、私が使用しています正規表現パターン:

=?(R\[[-0-9]*\]|RC) 

それは私に与えます:

result

しかし、数字だけを取得する必要があります。さらに、RCの代わりに0を取得する必要があります。

ありがとうございます!

+0

あなたはVBAマクロを使用していますか?これはVBAなしでは可能ではないようです。 – Slai

+0

@Slai、私はC#を使用しています – Nolesh

+0

'(RC?\ [ - ?[0-9] * \])'と関連するすべての結果をキャプチャして、 'C# 'R [x]'から必要なものがあれば、 'RC [y]'から '0'を得る。 – gwillie

答えて

0

あなたは非常に接近している - あなたは、あなたの正規表現で別のキャプチャグループを追加する場合R[x]からxを引き出すことができます。だからあなたの正規表現は次のようになります。

=?(R\[([-0-9]*)\]|RC)

それは[-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(); 

     } 
    } 
} 
1

私はそれをテストすることはできませんが、あなたはこのような何かを式の中で参照されているすべての行を取得することができます:

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