gpt4 book ai didi

java - 正则表达式提取括号值java

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:27:42 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用此代码:

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>

关于java - 正则表达式提取括号值java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19590910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com