[英]tokenizer or split string at multiple spaces in java
I need to tokenize a string where ever there is more than one space. 我需要标记一个字符串,其中有多个空格。
for instance 例如
"HUNTSVILLE, AL 30 39.8 44.3 52.3"
becomes 变
"HUNTSVILLE, AL","30","39.8","44.3","52.3"
StringTokenizer st = new StringTokenizer(str, " ");
just tokenizes any whitespace, and I can't figure out a regex to do what I need. 只是标记任何空格,我无法弄清楚正则表达式做我需要的。
Thanks 谢谢
Try this: 尝试这个:
String s = "HUNTSVILLE, AL 30 39.8 44.3 52.3";
String[] parts = s.split("\\s{3,}");
for(String p : parts) {
System.out.println(p);
}
The \\s
matches any white space char, and {3,}
will match it 3 or more times. \\s
匹配任何空格char, {3,}
将匹配3次或更多次。
The snippet above would print: 上面的代码段会打印出来:
HUNTSVILLE, AL 30 39.8 44.3 52.3
Can't you use split? 你不能用拆分吗?
String[] tokens = string.split(" ");
You have to filter empty entries though. 您必须过滤空条目。
Try this way: 试试这种方式:
String[] result = "HUNTSVILLE, AL 30 39.8 44.3 52.3".split("[ ]{2,}");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
[ ] - Represents space [] - 代表空间
{2,} - Represents more than 2 {2,} - 代表超过2个
/*
* Uses split to break up a string of input separated by
* whitespace.
*/
import java.util.regex.*;
public class Splitter {
public static void main(String[] args) throws Exception {
// Create a pattern to match breaks
Pattern p = Pattern.compile("[ ]{2,}");
// Split input with the pattern
String[] result =
p.split("one,two, three four , five");
for (int i=0; i<result.length; i++)
System.out.println(result[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.