如何在Java中拆分以下内容:
(1,2),(3,4),(5,6)
成:
1,2
3,4
5,6
我试过了:
test.split("(?<=\\()(.*)(?=\\))");
没有运气。
答案 0 :(得分:7)
您应该在)
,),(
或)
上拆分(然后手动删除空值,除非有一些我不知道的东西),如果你想分手。
test.split("\\),\\(|\\)|\\(");
虽然...匹配可能更简单。
"\\(([^\\)]*)\\)"
答案 1 :(得分:2)
您是否必须在一条线上完成所有操作?足够简单,可以将其分解成碎片,例如:
public static void main(String[] args) {
String test = "(1,2),(3,4),(5,6)";
String[] firstSplit = test.split("\\),\\(");
for (String token : firstSplit) {
token = token.replaceAll("[\\(\\)]*", "");
System.out.println(token);
}
}
答案 2 :(得分:2)
嗯...我认为如果你只是使用匹配(而不是split()
调用),这个正则表达式会起作用:
/\([^\)]+\)/g
所以在Java中我认为那将是......
Pattern p = Pattern.compile("\\([^\\)]+\\)");
Matcher m = p.matcher("(1,2),(3,4),(5,6)");
while(m.find()) {
java.lang.System.out.println(m.group());
}
答案 3 :(得分:2)
在使用Boost正则表达式引擎的TextPad中,它捕获数字
(\b\d+,\d+\b)
并且它捕获了两者之间:
((?:\),\()|(?:(?<!,)\()|(?:\)(?!,)))
免间隔:
( #Capture one of these three (quoted) things:
(?:
\),\( # "),(" <--Must be the first option!
)
|
(?:
(?<!,)\( # [not-a-comma]"("
)
|
(?:
\)(?!,) # ")"[not-a-comma]
)
)
Java程序:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
<P><CODE>java NumCommaNumSplitXmpl</CODE></P>
**/
public class NumCommaNumSplitXmpl {
public static final void main(String[] igno_red) {
String sToSearch = "(1,2),(3,4),(5,6)";
System.out.println("Capture numbers:");
String sFindNumCommaNum = "(\\b\\d+,\\d+\\b)";
Matcher m = Pattern.compile(sFindNumCommaNum).matcher(sToSearch);
while(m.find()) {
System.out.println(m.group());
}
System.out.println("Capture betweens:");
String sFindBetweens = "((?:\\),\\()|(?:(?<!,)\\()|(?:\\)(?!,)))";
m = Pattern.compile(sFindBetweens).matcher(sToSearch);
while(m.find()) {
System.out.println(m.group());
}
}
}
输出:
[C:\javastuff\]java NumCommaNumSplitXmpl
Capture numbers:
1,2
3,4
5,6
Capture betweens:
(
),(
),(
)
这是一个有趣的问题。
答案 4 :(得分:1)
公共类MainTest {
public static void main(String[] args){
String msg = "(1,2),(3,4),(5,6)";
String fmt = "(\\(|\\)\\,\\()|(\\(|\\))";
String tokens[] = msg.split(fmt);
for(String token: tokens) {
System.out.println(token);
}
Pattern p = Pattern.compile("[0-9]+,[0-9]+");
Matcher m = p.matcher("(1,2),(3,4),(5,6)");
while(m.find()) {
java.lang.System.out.println(m.group());
}
}
}