使用正则表达式分割字符串

时间:2014-11-18 18:28:01

标签: java regex

我正在尝试使用带有Java的正则表达式拆分String。 字符串如下所示:{'tata','toto','titi'}{}描述了前一个自由主义者的顺序,所以它对我不起作用。

我应该使用什么正则表达式来获得这个结果:

tata
toto
titi

3 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式:

String str = "{'tata','toto','titi'}";
String[] arr = str.split("[{},']+");
//=> tata, toto, titi

无需在字符类中转义{}

答案 1 :(得分:1)

您可以使用\禁用正则表达式中任何字符的特殊含义。

由于\本身在String中具有特殊含义,因此如果直接在java中的字符串文字中指定正则表达式,则需要复制它。因此,请将"{something}"替换为\\{something\\}"

答案 2 :(得分:1)

String a = "{'tata','toto','titi'}"
a = a.replace("{'", ""); // get rid of opening bracket and singlequote
a = a.replace("'}", ""); // get rid of ending bracket and singlequote
String[] b = a.split("','"); // split on commas surrounded by singlequotes

这应该会给你一个你想要的单词数组。我想这不是特定的正则表达式,但无论如何它应该做正确的事。

相关问题