比如说 String str = ": one two three ";
for(String s:str.split("[\\s:]")){
System.out.println(s);
}
这样出来就会one
two
three
前面多了两个"",我只想要one two three怎么写?
for(String s:str.split("[\\s:]")){
System.out.println(s);
}
这样出来就会one
two
three
前面多了两个"",我只想要one two three怎么写?
//在这里加一个if判断一下就可以了。
System.out.println(s);
}
if(s!=null) System.out.println(s);
}
/******************************************************************************
* 楼上说得没有错,你需要一个if来判一下把你不需要的空字符串过滤掉就可以了,
* 还有一点儿小小的BUG就是,字符串的比较应该用equals
*****************************************************************************/
package cn.com.hrbbaby.www;public class Test1
{ /**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
String strSample = ": one two three" ;
for ( String strTemp : strSample.split("[\\s|:]"))
{
if ( !strTemp.equals("") )
{
System.out.println(strTemp);
}
}
}}
也许我给的例子太简单了。如果我的分号散落在字符的各处呢?有如String str = "one,.two.three,four" 我想得到one two three four四个单词。我用[,.]分的话也会出现""字符串,我明白是由于连续匹配的原因。难道就只有判断是否为""?
String str = "one,.two.three,four";
for(String s:str.split("\\W")){
System.out.println(s);
}
package com.ricky.www;import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;public class Test{
public static void main(String[] args){
String regex = "(\\w+)";
String str = ": one two three ";
ArrayList<String> list = getStrings(str,regex);
int i = 1 ;
for(String str1 : list){
System.out.println(i++ + ": " + str1);
}
} public static ArrayList<String> getStrings(String str,String regex){
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
ArrayList<String> list = new ArrayList<String>();
while(matcher.find()){
list.add(matcher.group(1));
}
return list;
}
}何必要想得那么复杂呢?直接用//w+来匹配就可以啦
用正则表达式,
import java.util.regex.*;
Pattern p=Pattern.compile("\\w+");
Matcher m=p.matcher();
while(m.find())
{
System.out.println(m.group);}
...