2016-08-19 36 views
2

我想写一个正则表达式提取parameter1func1(parameter1, parameter2)parameter2,从1 parameter1parameter2范围的长度为64。爪哇正则表达式的函数内匹配参数

(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\)) 

我的版本可以不处理下列情况下(嵌套函数)

func2(func1(ef5b, 7dbdd)) 

我总是得到一个“7dbdd)”为parameter2。我怎么能解决这个问题?

回答

1

使用[^)]{1,64}(符合所有除)),而不是.{1,64}(匹配任意)马上停止之前,首先)

(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\)) 
           ^
           replace . with [^)] 

例子:

// remove whitespace and escape backslash! 
String regex = "(func1)(\\()(.{1,64})(,\\s*)([^)]{1,64})(\\))"; 
String input = "func2(func1(ef5b, 7dbdd))"; 
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern 
Matcher m = p.matcher(input); // java.util.regex.Matcher 
if(m.find()) { // use while loop for multiple occurrences 
    String param1 = m.group(3); 
    String param2 = m.group(5); 

    // process the result... 
} 

如果您想要忽略空白令牌,请使用这一个:

func1\s*\(\s*([^\s]{1,64})\s*,\s*([^\s\)]{1,64})\s*\)" 

示例:

// escape backslash! 
String regex = "func1\\s*\\(\\s*([^\\s]{1,64})\\s*,\\s*([^\\s\\)]{1,64})\\s*\\)"; 
String input = "func2(func1 (ef5b, 7dbdd))"; 
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern 
Matcher m = p.matcher(input); // java.util.regex.Matcher 
if(m.find()) { // use while loop for multiple occurrences 
    String param1 = m.group(1); 
    String param2 = m.group(2); 

    // process the result... 
} 
3

使用 “任何东西,但右括号”([^)]),而不是简单的 “东西”(.):

(func1) (\() (.{1,64}) (,\s*) ([^)]{1,64}) (\)) 

演示:https://regex101.com/r/sP6eS1/1

0

希望这是很有帮助的

func1[^\(]*\(\s*([^,]{1,64}),\s*([^\)]{1,64})\s*\) 
0
(func1) (\() (.{1,64}) (,\\s*) ([^)]{1,64}) (\)) 
0
^.*(func1)(\()(.{1,64})(,\s*)(.{1,64}[A-Za-z\d])(\))+ 

工作例如:here