我从数据库中提取数据并试图操纵结果字符串:
public class Main {
public static void main(String[] args) {
Connection sqlConn = connectSQL();
ResultSet rs;
Statement select;
try {
select = sqlConn.createStatement();
rs = select
.executeQuery("SELECT DISTINCT TSK.PointPerson FROM Task AS TSK LEFT JOIN [User] AS USR ON USR.DisplayName = TSK.PointPerson WHERE USR.DisplayName IS NULL AND TSK.PointPerson IS NOT NULL");
while (rs.next()) {
String displayName = rs.getString(1);
System.out.println(displayName);
if (displayName.contains("(")) {
String[] splittedString = displayName.split("(");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
我在这一行收到错误:String[] splittedString = displayName.split("(");
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1
(
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.accept(Unknown Source)
at java.util.regex.Pattern.group0(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.split(Unknown Source)
at java.lang.String.split(Unknown Source)
at Main.main(Main.java:21)
我不明白为什么会这样。如果我删除该行它工作正常。我得到的结果如下:
Dipankar XYZ(pradhand)
Rocky XYZ
正如你所看到的,有些人有'('而有些人没有。我试图用我的if语句来容纳这个。
我做错了什么?
答案 0 :(得分:4)
split
使用正则表达式作为参数,(
是正则表达式元字符,在本例中为groups。要使其成为文字,您需要使用split("\\(")
或split("[(]")
来转义它。