当前位置 博文首页 > 静Yu的博客:String类的方法中常用的正则表达式
? split() 方法中的正则表达式
? replaceAll() 方法中的正则表达式
? String类的对象方法split(regex)用regex把字符串分隔成若干个子串。
? 下面的例子求一行中被一个英文逗号和若干个空白符分隔的数的和:
import java.util.regex.*;
public class TestRegexSplit {
public static void main(String[] args){
String str = "28.35 , \t 71.53, \t\t 0.12 \t, ";
String regexString = "\\s*,\\s*";
String[] subs = str.split(regexString);
double sum = 0.0;
for (int i=0; i<subs.length; i++) {
double d = Double.parseDouble(subs[i].trim());
sum += d;
}
System.out.println(sum);
}
} // 程序的运行结果是100.0
? 英文一般用空格分隔两个单词,但由于输入错误,
会出现多个空格分隔两个单词的情况。下面的程
序把字符串中的多个空格替换为单个空格
import java.util.regex.*;
public class TestSearch {
public static void main(String[] args){
String str = "To be or not to be, that is the question.";
String res = str.replaceAll(" {2,}", " ");
System.out.println(res);
}
}
程序的运行结果是:To be or not to be, that is the question.
其中的replaceAll(regex, replacement)把符合regex的匹配内容全部更换成replacement
cs