正则表达式拆分字符串

时间:2013-09-05 04:40:45

标签: java regex

我有一个这样的字符串:

void methodname(String s1, String s2) //there can be any no of parameters

我希望正则表达式得到这样的最终字符串:

methodname(s1,s2)

请帮帮我

3 个答案:

答案 0 :(得分:1)

你可以试试这个。它也适用于对象,但也许有更好的方法来做到这一点或更好REGEX

    String str = "void methodname(String s1, String s2)";

    Pattern pattern = Pattern.compile("\\w\\s+([\\w_]+\\()(.*\\))");
    Matcher m1 = pattern.matcher(str);

    if (m1.find()) {

      String res = m1.group(1);
      Matcher m2 = Pattern.compile(",?\\s?\\w+\\s+(\\w+\\)?)").matcher(m1.group(2));

      int i = 0;
      while (m2.find()) {
        if (i > 0) {
          res += ",";
        }
        res += m2.group(1);
        i++;
      }

      System.out.println(res);
    }

输出:

    methodname(s1,s2)

答案 1 :(得分:0)

在Perl中,像这样

$str = "void  methodname(String s1, String s2)";
$str =~ s/void//;
$str =~ s/String//;

答案 2 :(得分:0)

为什么你不能使用替换方法而不是正则表达式。

String inputString="void methodname(String s1, String s2)";
inputString=inputString.replace("void ","");  //Replace "void " with empty string
inputString=inputString.replace("String ","");  //Replace "String " with empty string
相关问题