正则表达式在括号中提取值java

时间:2013-10-25 13:15:20

标签: java regex

我需要提取看起来像这样的字符串的值:

nameClass (val1)(val2)

拥有:

nameClass
val1
val2

问题在于它也必须适用于此:

nameClass

nameClass (val1)(val2)(val1)...(valn)

我尝试创建正则表达式,但它只适用于

nameClass (val1)(val2)

变体,看起来像这样(经过 Viorel Moraru 改进后):

String pattern = "((?:[a-z]+[A-Z][a-z]+))(([ |(]+)([-|+]?\\d+)([ |(|)]+)([-|+]?\\d+)([ |)]+))*";

如何使模式适用于所有

nameClass

nameClass (val1)(val2)(val1)...(valn)

Java代码:

String txt = "inputTestdata(12)(-13)";
String patern = "((?:[a-z]+[A-Z][a-z]+))([ |(]+)([-|+]?\\d+)([ |(|)]+)([-|+]?\\d+)([ |)]+)";

Pattern p = Pattern.compile(patern);
Matcher m = p.matcher(txt);
if (m.find())
{
  for (int i = 1; i < m.groupCount(); i ++)
  {
   System.out.print(m.group(i) + "\n");
  }
}

3 个答案:

答案 0 :(得分:4)

您可以使用此代码:

String s = "nameClass(val1)(val2)(val3)";
Pattern p = Pattern.compile("^(\\w+) *(.*)$");
Matcher m = p.matcher(s);
String ps = "";
if (m.matches())
{
  ps = m.group(2);
  System.out.printf("Outside parantheses:<%s>\n", m.group(1));
}
Pattern p1 = Pattern.compile("\\(([^)]*)\\)");
Matcher m1 = p1.matcher(ps);
while (m1.find())
{
  System.out.printf("Inside parentheses:<%s>%n", m1.group(1));
}

<强>输出:

Outside parantheses:<nameClass>
Inside parentheses:<val1>
Inside parentheses:<val2>
Inside parentheses:<val3>

答案 1 :(得分:3)

假设:

  • 您的输入无需在开始时进行验证 nameClass
  • 您想要清理括号(因为您的问题目前让我理解)

...为什么不用括号替换括号内的所有内容?

例如:

Pattern p = Pattern.compile("\\((.+?)\\)");
String[] inputs = {"nameClass", "nameClass (var1)", "nameClass (var1) (var2)"};
Matcher m;
for (String input: inputs) {
    m = p.matcher(input);
    System.out.println("Input: " + input + " --> replacement: " + m.replaceAll("$1"));
    // resetting matcher after "replaceAll" and accessing values directly by group 1 reference
    m.reset();
    while (m.find()) {
        System.out.println("\tFound value: " + m.group(1));
    }
}

输出:

Input: nameClass --> replacement: nameClass
Input: nameClass (var1) --> replacement: nameClass var1
    Found value: var1
Input: nameClass (var1) (var2) --> replacement: nameClass var1 var2
    Found value: var1
    Found value: var2

答案 2 :(得分:0)

我不是正则表达式专家,但这有用吗?

\s*\w+\s*(\(\w+\))*