[Java] String.split() 分割字串函式要使用Regular Expression

  • 0
當我試著要這麼做的時候
// insert [table_name] values (SID SNAME SPOINT1 SPOINT2)
 String[] cmd_i = input.split(" ");
 String i_table = cmd_i[1];  
 String[] tuple_split1 = input.split("(");
就會出現以下error message


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.(Unknown Source)
 at java.util.regex.Pattern.compile(Unknown Source)
 at java.lang.String.split(Unknown Source)
 at java.lang.String.split(Unknown Source)

Solution I
其實split()中的參數需改為正規表達式(Regular expression),換成:
String[] tuple_split1 = input.split("\\(");
左右括號的跳脫符號是 "\\(" 跟 "\\)"
--

Solution II
也可以使用Java有個內建的字串處理函式: replace  或是 replaceAll
但是請注意這兩個函式的參數不一樣
假設您想將字串s = "(abc)" 替換成 _abc_
可以使用
s.replace("(", "_");
或是
s.replaceAll("\\(", "_")

看出來差別了嗎?
replaceAll中,傳進的必須是正規表達式(Regular Expression)

請參考 http://stackoverflow.com/questions/2033161/string-pattern-matching-problem-in-java


The first argument to string.replaceAll is a regular expression, not just a string. The opening left bracket is a special character in a regex, so you must escape it:

line.replaceAll("\\(", "_");

Alternatively, since you are replacing a single character, you could use string.replace like so:

line.replace('(', '_');

沒有留言 :

張貼留言