[英]Removing special characters from string
I want to parse this string into a list and return {1.193493, 54.6333, 2.093077, 31.6235, 6.175355, 21.6479}. 我想将此字符串解析为一个列表,然后返回{1.193493、54.6333、2.093077、31.6235、6.175355、21.6479}。 How do I get rid of the square brackets????
如何摆脱方括号???? I used a for loop and replace but it doesn't work.
我使用了for循环和替换,但是它不起作用。
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]"
String[] parsed = st.split(",");
for (String next : parsed) {
next.replace("//[", "").replace("//]", "");
}
replace()
works with plain Strings, not regex. replace()
适用于纯字符串,不适用于正则表达式。 Therefore you can simply use: 因此,您可以简单地使用:
next.replace("[", "").replace("]", "");
Also notice that you need to assign it to some string variable; 还要注意,您需要将其分配给一些字符串变量; assigning it to
need
won't work (won't modify elements in parsed
array). 将其分配给
need
将不起作用(不会修改parsed
数组中的元素)。
You should actually remove the braces first and split
later, like this: 实际上,您应该先删除括号然后再
split
,如下所示:
String[] parsed = st.replace("[", "").replace("]", "").split(",");
You can do this with one line: 您可以使用一行来完成此操作:
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
Full code: 完整代码:
package com.stackoverflow;
import java.util.Arrays;
import java.util.List;
public class Demo
{
public static void main(String[] args)
{
String t = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
for(String s : list)
{
System.out.println(s);
}
}
}
Converts string to list of strings and prints it. 将字符串转换为字符串列表并打印。 If you need to convert strings to doubles, use
Double.parseDouble(s)
in loop. 如果需要将字符串转换为双精度型,请在循环中使用
Double.parseDouble(s)
。
您可以使用此正则表达式一次完成所有操作:
(?:\D*(\d*\.\d*))+
You could achieve your goal in two steps. 您可以分两步实现目标。
1) Remove all special characters except comma (,) 1)删除除逗号(,)以外的所有特殊字符
2) Then split by comma (,) 2)然后以逗号(,)分隔
public static void main(String[] args) {
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
String[] parsed = st.replaceAll("[^\\d.,]+", "").split(",");
}
Output: 输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.