java 11 字符串新方法 lines() 方法 repeat() isBlank() 字符串格式化 String.format(); System.out.printf(); 格式化輸出 %s %d %f %tF String.format(); 返回格式化后的字符串 %s 字符串 %d 數字 %03d 3位數字 %f 小數 %t 制表位 正則表達式? 字符串模式 規則 正則表達應用領域:字符搜索 檢查 替換 String 對象中支持正則表達式的方法 ReplaceAll() 替換 match() 匹配 split() 拆分 java 正則表達式工具類 java.util.regex包下 Pattern 模式類 Matcher 匹配器類 \\d 代表1位數字 [0-9] 代表1位數字 [1,3,5] 代表1位數字,范圍在135 * 代表前邊元字符,0個或多個 {0,} . 任意字符 + {1,} ? {0,1} {n} () | .*[0-9].* 數字 .*[a-zA-Z].* 字母 .*[\u4e00-\u9fa5]{3}.* 漢字 1、正則表達式實現判斷有沒有數字,有沒有中文,有沒有英文, 手機號判斷格式
public class Zuo2 {
public static void main(String[] args) {
String str="cdsgf第三個776";
if(str.matches(".*\\d.*")) {
System.out.println("含有數字");
}else {
System.out.println("不含數字");
}
if(str.matches(".*[\\u4e00-\\u9fa5].*")) {
System.out.println("含有中文");
}else {
System.out.println("不含中文");
}
if(str.matches(".*[a-zA-Z].*")) {
System.out.println("含有英文");
}else {
System.out.println("不含英文");
}
str=str.replaceAll("\\d","");
System.out.println(str);
str ="13798797927";
if(str.matches("1[3,5,7,,8,9]\\d{9}")) {
System.out.println("是電話號");
}else {
System.out.println("不是電話號");
}
}
3、求字符串中所有數字的和
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Zuo3 {
public static void main(String[] args) {
String s="0f8oi324oi3r2893r3jur0yr";
Pattern p=Pattern.compile("\\d{1,}");
Matcher m=p.matcher(s);
System.out.println(p);
System.out.println(m);
// System.out.println(m.find());
int sum=0;
StringBuilder str=new StringBuilder();
while(m.find()) {
String temp=m.group();
sum+=Integer.parseInt(temp);
str.append(temp+"+");
}
str.replace(str.length()-1, str.length(), "=");
System.out.println(str.toString()+sum);
}
}