2016-04-03 81 views
1

我试图从一串使用正则表达式的pascal代码中提取参数名,这是我尝试使用的最复杂的。请注意,永远不会有空白区域,圆括号将始终存在。在java正则表达式中捕获同一组的多个实例

(rate:real;interest,principal:real) 

我目前得到了重新如下:

[(](?:([\w]*)(?:[:][\w])?[;|,]?)*[)] 

我希望作为再经过参数我可以访问每一个捕获组,但显然我不能。对于上面的例子,我需要的值是“利率”,“利息”和“本金”。

有没有解决方案呢?我自己的努力导致我to here他们提到使用

“matcher()with while ... find()”。

我不完全理解正则表达式,并希望得到任何帮助。谢谢。

回答

1

您可以使用positive lookbehind此为

((?<=[\(,;])[A-Za-z_]\w*) 

正则表达式击穿

(
    (?<= #Positive look behind 
    [\(,;] #Finds all position that have bracket, comma and semicolon 
) 
    [A-Za-z_]\w* #After finding the positions, match all the allowed characters in variable name following that position 
) 

Regex Demo

String line = "(rate:real;interest,principal:real)"; 
String pattern = "((?<=[\\(,;])[A-Za-z_]\\w*)"; 

Pattern r = Pattern.compile(pattern); 
Matcher m = r.matcher(line); 

while (m.find()) { 
    System.out.println(m.group(1)); 
} 

Ideone Demo

+0

谢谢!这是我所需要的。 – LismUK

1

这里有一种方法用一个比较简单的正则表达式来做到这一点:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class RegexTest { 

    public static void main(String[] args) { 
     String simple = "(rate:real;interest,principal:real)"; 
     String regex = "(\\w+:|\\w+,)"; 

     Pattern p = Pattern.compile(regex); 
     Matcher m = p.matcher(simple); 

     while (m.find()) { 
      System.out.println(m.group().substring(0, m.group().length() - 1)); 
     } 
    } 
} 

我怕我不知道帕斯卡,但似乎你的名字后,要么以冒号或逗号结束。正则表达式查找这些字符串,然后删除最后一个字符(冒号或逗号)。

我从测试运行得到的输出是:

rate 
interest 
principal