Java中对正则表达式的支持

Java对正则表达式的支持

字符串

字符串中有对正则表达式的支持的方法:

  1. 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"));
    
  2. 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);
    
  3. 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);
    
  4. 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);
    }
}```

上一篇:vue.js帐号,密码,邮箱和移动手机号码正则验证


下一篇:密码强度校验