I don't use regex that much so I am having some troubles with this right now. I'm trying to replace ["item1", "item2"]
with item1, item2
using string.replaceAll()
. However, I don't know how do I match the [
, and I don't know how to replace all special characters but the comma.
我没有使用正则表达式,所以我现在遇到了一些麻烦。我正在尝试使用string.replaceAll()将item1,item2替换为[“item1”,“item2”]。但是,我不知道如何匹配[,而且我不知道如何替换所有特殊字符但逗号。
1 个解决方案
#1
2
You can use following regular expression to solve your problem.
您可以使用以下正则表达式来解决您的问题。
String s = "[\"item1\", \"item2\"]";
System.out.println(s.replaceAll("\\[\"([a-z0-9]*)\",\\s*\"([a-z0-9]+)\"\\]", "$1, $2"));
Note that I have use parenthesis to group what I wanted and use them in the replace string. Your groups will identify as $1, $2, $3... as it appears in your regular expression.
请注意,我使用括号来分组我想要的内容并在替换字符串中使用它们。您的群组将标识为正常表达式中显示的$ 1,$ 2,$ 3 ....
#1
2
You can use following regular expression to solve your problem.
您可以使用以下正则表达式来解决您的问题。
String s = "[\"item1\", \"item2\"]";
System.out.println(s.replaceAll("\\[\"([a-z0-9]*)\",\\s*\"([a-z0-9]+)\"\\]", "$1, $2"));
Note that I have use parenthesis to group what I wanted and use them in the replace string. Your groups will identify as $1, $2, $3... as it appears in your regular expression.
请注意,我使用括号来分组我想要的内容并在替换字符串中使用它们。您的群组将标识为正常表达式中显示的$ 1,$ 2,$ 3 ....