从具有模式的Excel公式提取列名称

我想从Excel公式中提取列名,但我可以用下面的代码得到的是最新的名字:

String formula = "IF(AB13=0,0,IF(+I13/AC13>100%,100%,+I13/AC13))"; Matcher matcher = Pattern.compile(".*\\W([AZ]+)\\d+.*").matcher(formula); while (matcher.find()) { System.out.println("Column name= "+matcher.group(1)); } 

我期待它显示

 "Column name= AB" "Column name= I" "Column name= AC" "Column name= I" "Column name= AC" 

但它只显示“列名= AC”。

我得到的事实是,我的模式的第一个“*”匹配整个formula => IF(AB13=0,0,IF(+I13/AC13>100%,100%,+I13第一部分formula => IF(AB13=0,0,IF(+I13/AC13>100%,100%,+I13但我不我不知道如何让它匹配所有的可能性。

在此先感谢您的帮助。

只要删除所有.*并且不需要\\W除非您的公式中也有该格式的文本(在这种情况下,在应用正则expression式之前,您必须删除引号内的所有内容):

 String formula = "IF(AB13=0,0,IF(+I13/AC13>100%,100%,+I13/AC13))"; Matcher matcher = Pattern.compile("([AZ]+)\\d+").matcher(formula); while (matcher.find()) { System.out.println("Column name= "+matcher.group(1)); } 

ideone演示

.*正在消耗所有其他的匹配,加上你并不需要将整个公式与模式匹配器匹配。

你太过于复杂。 你只是想匹配一个或多个字母,并声称后面跟着一个数字:

 [A-Za-z]++(?=\\d+) 

模式的第一部分与一个或多个A-Za-z相匹配,然后使用肯定的前瞻来断言该模式后面跟着一个数字。

例:

 public static void main(String[] args) throws Exception { String formula = "IF(AB13=0,0,IF(+I13/AC13>100%,100%,+I13/AC13))"; Matcher matcher = Pattern.compile("[A-Za-z]++(?=\\d+)").matcher(formula); while (matcher.find()) { System.out.println("Column name= " + matcher.group()); } } 

输出:

 Column name= AB Column name= I Column name= AC Column name= I Column name= AC