日期:2014-05-20 浏览次数:20751 次
public static void main(String[] args) {
String s="xxx(a,b,c,d)";
Pattern p = Pattern.compile("(\\w+)\\((.*)\\)");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
System.out.println(m.group(2));
}
}
public class MethodSignatureRegExp {
public static void main(String[] args) {
String m = "public List<int> foo(Type name, ...)";
// 名字,模板,类型的正则
String namePattern = "[_a-zA-Z]+\\w*";
String templatePattern = "(<[_a-zA-Z]+\\w*(, [_a-zA-Z]+\\w*)*>)?";
String typePattern = namePattern + templatePattern;
// 参数的正则
String argPatternZero = ""; // 无参数
String argPatternDynamic = "..."; // 动态参数
String argPattern = typePattern + " " + namePattern; // 一个参数
String argPatternOne = argPattern + "(, ...)?"; // 一个参数 + 动态参数
String argPatternMulti = argPattern + "(, " + argPattern + ")*(, ...)?"; // 多个参数 + 动态参数
String argsPattern = "(" + argPatternZero + "
------解决方案--------------------
" + argPatternDynamic + "
------解决方案--------------------
" + argPatternOne + "
------解决方案--------------------
" + argPatternMulti + ")";
// 方法签名的正则
String methodSignaturePattern = "(public
------解决方案--------------------
protected
------解决方案--------------------
private)( static)?( final)? " +
typePattern + " " + namePattern + "\\(" + argsPattern + "\\)";
// 每个部分的正则测试
System.out.println("List<int, Object>".matches(typePattern));
System.out.println("".matches(argPatternZero));
System.out.println("...".matches(argPatternDynamic));
System.out.println(argPatternOne);
System.out.println("int age".matches(argPatternOne));
System.out.println(argPatternMulti);
System.out.println("int age, List<Integer> values".matches(argPatternMulti));
System.out.println("int age, List<Integer> values, ...".matches(argsPattern));
// 测试是否一个方法的签名
// 暂时规则,单词间只用一个空格分隔,因为实现情况要考虑回车,多个空格,tab键等,把空格在正则中换成\\s+
// 例如要在','前后加\\s*,函数签名中的'(', ')'前后加\\s*
// 这里为了不使正则变得太难懂,直接只用了一个空格.
System.out.println(methodSignaturePattern);
System.out.println("public void foo()".matches(methodSignaturePattern));
System.out.println("public void foo(...)".matches(methodSignaturePattern));
System.out.println("public List<Integer> foo(String name, Set<Double> values, ...)".matches(methodSignaturePattern));
}
}