3

我需要提取如下所示的字符串的值:

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");
  }
}
4

3 回答 3

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>
于 2013-10-25T13:30:12.443 回答
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
于 2013-10-25T13:26:52.073 回答
0

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

\s*\w+\s*(\(\w+\))*
于 2013-10-25T13:27:13.110 回答