Java对正则表达式的支持
字符串
字符串中有对正则表达式的支持的方法:
-
matches(String regex)
底层是调用了
Pattern.matches(regex, this)
方法Scanner sc = new Scanner(System.in); System.out.println("请输入字母"); String str = sc.next(); System.out.println(str.matches("(.*)a"));
-
replaceFirst(String regex, String replacement)
底层是调用了
Pattern.compile(regex).matcher(this).replaceFirst(replacement)
方法Scanner sc = new Scanner(System.in); System.out.println("请输入字符串"); String str = sc.next(); String result = str.replaceFirst("a", "*");//把首个a替换为* System.out.println(result);
-
replaceAll(String regex, String replacement)
底层是调用了
Pattern.compile(regex).matcher(this).replaceAll(replacement)
方法String regex = "你好"; Scanner sc = new Scanner(System.in); System.out.println("请输入字符串"); String str = sc.next(); //String result = str.replaceAll(regex, "大家好"); String result = str.replaceAll("\\d", "*"); System.out.println(result);
-
replace(CharSequence target, CharSequence replacement)
底层是调用了
Pattern.compile(target.toString(), Pattern.LITERAL).matcher(this).replaceAll(Matcher.quoteReplacement(replacement.toString()))
方法String regex = "h"; Scanner sc = new Scanner(System.in); System.out.println("请输入字符串"); String str = sc.next(); //String con = str.replace("h", "*");//把字母h替换为* String con = str.replace("\\d", "*"); System.out.println(con);
注意:replace中的参数是target,而不是regex,即replace和replaceAll相比,相同点都是能够替换全部指定的字符串。不同点是replace不支持正则,只能传字符串。
真正的正则类
Pattern p = Pattern.compile(String regex);
Matcher m = p.matcher(CharSequence input);
m.find()/m.lookingAt()/m.matches()/...
package top.lukeewin.demo23;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo02Pattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
Pattern p = Pattern.compile("java");
Matcher m = p.matcher(input);
boolean matches = m.matches();//只有完全匹配才返回true
boolean b1 = m.lookingAt();//只有以java开始的,才返回true
boolean b2 = m.find();//任意位置有java,都返回true
boolean b3 = m.find(3);//从指定索引3开始找,有java,则返回true
System.out.println(matches);
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
}
}```