我正在尝试使用正则表达式在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
,1
,0
目前,我正在使用正则表达式模式:
=?(R\[[-0-9]*\]|RC)
它给了我:
但是只有获得数字才是必要的。此外,我必须获得RC
而不是0
。
提前致谢!
答案 0 :(得分:1)
我无法测试它,但您可以使用以下内容获取公式中引用的所有行:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# create some random data
data = pd.DataFrame(np.random.rand(11, 5), columns=['A', 'B', 'C', 'D', 'E'], index = ['yyyyyyyy - ' + str(x) for x in range(2000, 2011, 1)])
# plot heatmap
plt.ion()
ax = sns.heatmap(data.T)
# adjust to taste
ax.figure.subplots_adjust(bottom = 0.25)
# turn the axis label
for item in ax.get_yticklabels():
item.set_rotation(0)
for item in ax.get_xticklabels():
item.set_rotation(90)
# save figure
plt.savefig('seabornPandas.png', dpi=100)
答案 1 :(得分:0)
你非常接近 - 如果你在正则表达式中添加了另一个捕获组,那么你可以从x
中取出R[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();
}
}
}