分割:
·String类的功能:public String[] split(String regex)
public class Demo5_spilt {
public static void main(String[] args) {
String s = "小红 小黄 小绿";
String[] arr = s.split(" "); //通过正则表达式切割字符串
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
eg:把给定字符串中的数字排序
import java.util.Arrays;
public class Test1 {
/**
* @param args
* 需求:有一个字符串"91 27 46 38 50",请写代码实现最终输出结果是:"27 38 46 50 91"
*
* 分析
* 1。将字符串切割成字符串数组
* 2。将字符串转换成数字并将其存储在一个等长度的int数组中
* 3。排序
* 4。将排序后的结果遍历并拼接成一个字符串
*/
public static void main(String[] args) {
String s = "91 27 46 38 50";
String[] sArr = s.split(" ");
int[] arr = new int[sArr.length];
for(int i = 0; i < arr.length ; i++) {
arr[i] = Integer.parseInt(sArr[i]); //将数字字符串转换成数字
}
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < arr.length; i++) {
if(i == arr.length -1) {
sb.append(arr[i]);
}else {
sb.append(arr[i] + " ");
}
}
System.out.println(sb);
}
}
替换:
String类的功能:public String[] replaceAll(String regex,String replacement)
public class Demo6_replaceAll {
public static void main(String[] args) {
String s = "zhejiang2daxue";
String regex = "\\d";
String s2 = s.replaceAll(regex,"");
System.out.println(s2);
}
}
分组:
public static void main(String[] args) {
//需求:按照叠词切割“sdqqqfgkkkhjppppkl”
thing s = "sdqqqfgkkkhjppppkl";
String regex = "(.)\\1+"; //+代表第一组出现一次或多次
String[] arr = s.split(regex);
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
//需求:我我....我...我.要...要要...要上...上上..上.大..大大.大.学.学.学..学
//将字符串还原成“我要上大学”
String s = "我我....我...我.要...要要...要上...上上..上.大..大大.大.学.学.学..学";
String s2 = s.replaceAll("\\.+","");
String s3 = s2.replaceAll("(.)\\1+","$1") //$1代表第一组的内容
System.out.println(s3);
}
}
获取:
package com.heima.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo8_Pattern {
/**
* Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
*/
public static void main(String[] args) {
//demo1();
String s = "我的手机号码是18511866260,曾经用过18987654321,还用过18812345678";
String regex = "1[3578]\\d{9}"; //手机号码的正则表达式
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
/*boolean b1 = m.find();
System.out.println(b1);
System.out.println(m.group());
boolean b2 = m.find();
System.out.println(b2);
System.out.println(m.group());*/
while(m.find())
System.out.println(m.group());
}
public static void demo1() {
Pattern p = Pattern.compile("a*b"); //获取到正则表达式
Matcher m = p.matcher("aaaaab"); //获取匹配值
boolean b = m.matches(); //
System.out.println(b);
System.out.println("aaaaab".matches("a*b")); //
}
}