Java教程

Java 正则表达式

Java正则表达式或正则表达式是一种API,用于搜索或操作字符串的模式。
它广泛用于定义对字符串的约束,例如密码和电子邮件验证。学习完Java regex教程之后,您将可以使用Java Regex Tester工具测试您的正则表达式。
Java Regex API在 java.util.regex 中提供了1个接口和3个包。

java.util.regex包

Matcher和Pattern类提供Java正则表达式的功能。 java.util.regex包为正则表达式提供了以下类和接口。
MatchResult接口 Matcher类 Pattern类 PatternSyntaxException类 Java Regex API

Matcher类

它实现 MatchResult 接口。这是一个 regex引擎,用于对字符序列执行匹配操作。
方法 说明
boolean matchs() 测试正则表达式是否与模式匹配。
boolean find() 查找与模式匹配的下一个表达式。
boolean find(int start) 从给定的起始编号中查找与模式匹配的下一个表达式。
String group() 返回匹配的子序列。
int start() 返回匹配子序列的起始索引。
int end() 返回匹配子序列的结束索引。
int groupCount() 返回匹配的子序列的总数。

Pattern类

它是正则表达式的编译版本。用于定义正则表达式引擎的模式。
方法 说明
static Pattern compile(String regex) 编译给定的正则表达式并返回Pattern的实例。
Matcher matcher(CharSequence input) 创建一个匹配器,将给定输入与模式匹配。
static boolean matches(String regex, CharSequence input) 它作为编译和匹配方法的组合。它会编译正则表达式,并将给定的输入与模式匹配。
String[] split(CharSequence input) 将给定的输入字符串拆分为给定模式的匹配项。
String pattern() 返回正则表达式模式。

Java正则表达式示例

有三种方法可以用Java编写正则表达式示例。
import java.util.regex.*;
public class RegexExample1{
    public static void main(String args[]){
        Pattern p = Pattern.compile(".s");
        Matcher m = p.matcher("as");
        boolean b = m.matches();
        boolean b2=Pattern.compile(".s").matcher("as").matches();
        boolean b3 = Pattern.matches(".s", "as");
        System.out.println(b+" "+b2+" "+b3);
    }
}

输出

truetrue true

正则表达式.示例

.(点)代表一个字符。
import java.util.regex.*;
class RegexExample2{
    public static void main(String args[]){
        System.out.println(Pattern.matches(".s", "as"));
        System.out.println(Pattern.matches(".s", "mk"));
        System.out.println(Pattern.matches(".s", "mst"));
        System.out.println(Pattern.matches(".s", "amms"));
        System.out.println(Pattern.matches("..s", "mas"));
    }
}

正则表达式字符类

角色类 说明
[abc] a,b或c(简单类)
[^ abc] 除a,b或c(取反)之外的任何字符
[a-zA-Z] a到z或A到Z,包括端点(范围)
[a-d [m-p]] a到d,或m到p: [a-dm-p](联合)
[a-z && [def]] d,e或f(交叉点)
[a-z && [^ bc]] a到z,b和c除外: [ad-z](减法)
[a-z && [^ m-p]] a到z,而不是m到p: [a-lq-z](减法)

正则表达式字符类示例

import java.util.regex.*;
class RegexExample3{
    public static void main(String args[]){
        System.out.println(Pattern.matches("[amn]", "abcd"));
        System.out.println(Pattern.matches("[amn]", "a"));
        System.out.println(Pattern.matches("[amn]", "ammmna"));
    }
}

正则表达式量词

量词指定字符出现的次数。
正则表达式 说明
X? X发生一次或根本不发生
X + X发生一次或多次
X * X发生零次或多次
X {n} X仅出现n次
X {n,} X出现n次或更多次
X {y,z} X发生至少y次但少于z次

正则表达式字符类和量词示例

import java.util.regex.*;
class RegexExample4{
    public static void main(String args[]){
        System.out.println("? quantifier ....");
        System.out.println(Pattern.matches("[amn]?", "a"));
        System.out.println(Pattern.matches("[amn]?", "aaa"));
        System.out.println(Pattern.matches("[amn]?", "aammmnn"));
        System.out.println(Pattern.matches("[amn]?", "aazzta"));
        System.out.println(Pattern.matches("[amn]?", "am"));
        System.out.println("+ quantifier ....");
        System.out.println(Pattern.matches("[amn]+", "a"));
        System.out.println(Pattern.matches("[amn]+", "aaa"));
        System.out.println(Pattern.matches("[amn]+", "aammmnn"));
        System.out.println(Pattern.matches("[amn]+", "aazzta"));
        System.out.println("* quantifier ....");
        System.out.println(Pattern.matches("[amn]*", "ammmna"));
    //true (a or m or n may come zero or more times)}
}

正则表达式元字符

正则表达式元字符用作简码。
正则表达式 说明
. 任何字符(可能匹配终止符,也可能不匹配)
\ d 任何数字,少于[0-9]
\ D 任何非数字,是[^ 0-9]的缩写
\ s 任何空格字符,是[\ t \ n \ x0B \ f \ r]的缩写
\ S 任何非空白字符,是[^ \ s]的缩写
\ w 任何单词字符,是[a-zA-Z_0-9]的缩写
\ W 任何非单词字符,是[^ \ w]的缩写
\ b 单词边界
\ B 非单词边界

正则表达式元字符示例

import java.util.regex.*;
class RegexExample5{
    public static void main(String args[]){
        System.out.println("metacharacters d....");
        \\d means digitSystem.out.println(Pattern.matches("\\d", "abc"));
        System.out.println(Pattern.matches("\\d", "1"));
        System.out.println(Pattern.matches("\\d", "4443"));
        System.out.println(Pattern.matches("\\d", "323abc"));
        System.out.println("metacharacters D....");
        \\D means non-digitSystem.out.println(Pattern.matches("\\D", "abc"));
        System.out.println(Pattern.matches("\\D", "1"));
        System.out.println(Pattern.matches("\\D", "4443"));
        System.out.println(Pattern.matches("\\D", "323abc"));
        System.out.println(Pattern.matches("\\D", "m"));
        System.out.println("metacharacters D with quantifier....");
        System.out.println(Pattern.matches("\\D*", "mak"));
    }
}

正则表达式问题1

import java.util.regex.*;
class RegexExample6{
    public static void main(String args[]){
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "kkvarun32"));
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));
        System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"));
    }
}

正则表达式问题2

import java.util.regex.*;
class RegexExample7{
    public static void main(String args[]){
        System.out.println("by character classes and quantifiers ...");
        System.out.println(Pattern.matches("[789]{1}[0-9]{9}", "9953038949"));
        System.out.println(Pattern.matches("[789][0-9]{9}", "9953038949"));
        System.out.println(Pattern.matches("[789][0-9]{9}", "99530389490"));
        System.out.println(Pattern.matches("[789][0-9]{9}", "6953038949"));
        System.out.println(Pattern.matches("[789][0-9]{9}", "8853038949"));
        System.out.println("by metacharacters ...");
        System.out.println(Pattern.matches("[789]{1}\\d{9}", "8853038949"));
        System.out.println(Pattern.matches("[789]{1}\\d{9}", "3853038949"));
    }
}

Java Regex Finder示例

import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.regex.Matcher;
public class RegexExample8{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while (true) {
            System.out.println("Enter regex pattern:");
            Pattern pattern = Pattern.compile(sc.nextLine());
            System.out.println("Enter text:");
            Matcher matcher = pattern.matcher(sc.nextLine());
            boolean found = false;
            while (matcher.find()) {
                System.out.println("I found the text "+matcher.group()+" starting at index "+ matcher.start()+" and ending at index "+matcher.end());
                found = true;
            }
            if(!found){
                System.out.println("No match found.");
            }
        }
    }
}
输出:
Enter regex pattern: java
Enter text: this is java, do you know java
I found the text java starting at index 8 and ending at index 12
I found the text java starting at index 26 and ending at index 30
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4