1.Java正则表达式基础

1.首先,我们需要清楚Java中那些地方支持正则表达式

1)matches()方法
此方法用来判断字符串是否符合指定正则表达式的规则,如果符合就返回true,否则返回false
示例:

public static void main(String[] args) {
    
    
    String str = "成都市(成华区)(武侯区)(高新区)";
    String str1="哈哈";
    boolean result = str1.matches("哈哈");
    System.out.println("String.matches方法执行结果:"+result);
}

2)replaceAll()方法

//此方法使用正则表达式模式替换,将所有符合正则表达式的部分替换为后面的字符串
String str1="哈哈,我是你爸爸";
str1=str1.replaceAll("哈哈","嗨嗨");
System.out.println(str1);

3)replaceFirst()方法

//此方法使用正则表达式模式替换第一个符合模式的字符串
String str1="哈哈,我是你爸爸";
str1=str1.replaceFirst("嗨嗨","叽叽");
System.out.println(str1);

4)split()方法

//此方法使用正则表达式对字符串进行拆分,组成一个String数组
String str1="哈哈,我是你爸爸";
String[] result1=str1.split(",");
System.out.println(result1[0]);
System.out.println(result1[1]);

除此之外,Java还专门有一个支持正则表达式的包:java.util.regex
里面有两个类
Pattern 类:
pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。

Matcher 类:
Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。

PatternSyntaxException:
PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。

完整实例如下:

package Regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式学习,java那些地方支持正则表达式
 */
public class RegexStudy {
    
    
    public static void main(String[] args) {
    
    
        String str = "成都市(成华区)(武侯区)(高新区)";
        String str1="哈哈,我是你爸爸";
        //首先是String类中支持正则表达式的方法
        //matches方法:此方法用来判断字符串是否符合指定正则表达式的规则,如果符合就返回true,否则返回false
        boolean result = str1.matches("哈哈");
        System.out.println("String.matches方法执行结果:"+result);
        //replaceAll方法:此方法使用正则表达式模式替换,将所有符合正则表达式的部分替换为后面的字符串
        str1=str1.replaceAll("哈哈","嗨嗨");
        System.out.println(str1);
        //replaceFirst方法:此方法使用正则表达式模式替换第一个符合模式的字符串
        str1=str1.replaceFirst("嗨嗨","叽叽");
        System.out.println(str1);
        //split方法:此方法使用正则表达式对字符串进行拆分,组成一个String数组
        String[] result1=str1.split(",");
        System.out.println(result1[0]);
        System.out.println(result1[1]);

        //获得一个正则表达式对象
        Pattern p = Pattern.compile(".*?(?=\\()");
        //使用正则表达式对象处理指定字符串,并获得结果对象
        Matcher m = p.matcher(str);
        //从正则表达式结果对象中获得信息
        if(m.find()) {
    
    
            System.out.println(m.group());
        }
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/c1776167012/article/details/121912710
今日推荐