【新手向】从零开始学习Java(Day12)正则表达式

每天二十分钟,成就Java大神,点点关注不迷路!

今天是第十二天,给坚持到这里的小伙伴点个赞!

成功的人无非是主动选择与痛苦共处,共勉!


目录

正则表达式

java.util.regex 包

捕获组

例子

Java的正则表达式特殊语法

Matcher 类的方法

索引方法

查找方法

替换方法

PatternSyntaxException 类的方法

下节预告


正则表达式

      正则表达式定义了字符串的模式,可以用来搜索、编辑或处理文本,它并不仅限于某一种语言,但是在每种语言中有细微的差别。

      正则表达式的基础内容请看:一文搞懂 正则表达式

      Java 提供了 java.util.regex 包,用于处理正则表达式的匹配操作。

java.util.regex 包

      java.util.regex 包是 Java 标准库中用于支持正则表达式操作的包,它主要包含以下三类:

1.Pattern 类:pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数

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

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

捕获组

      我们在正则表达式中介绍过,捕获组是把多个字符当一个单独单元进行处理的方法,它通过对括号内的字符分组来创建。例如,正则表达式 (dog) 创建了单一分组,组里包含"d","o",和"g"三个字符。

      捕获组是通过从左至右计算其开括号来编号。例如,在表达式((A)(B(C))),有四个这样的组:

((A)(B(C)))

(A)

(B(C))

(C)

      通过调用 matcher 对象的 groupCount 方法可以查看表达式有多少个分组,groupCount 方法返回一个 int 值。

      还有一个特殊的组(group(0)),它总是代表整个表达式。该组不包括在 groupCount 的返回值中。

例子

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
    public static void main( String[] args ){

      String line = "This order was placed for QT3000! OK?";
      String pattern = "(\\D*)(\\d+)(.*)";//(非数字)(数字)(其他字符)
 
      Pattern r = Pattern.compile(pattern);// 创建 Pattern 对象
      Matcher m = r.matcher(line);// 创建 matcher 对象

      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
         System.out.println("Found value: " + m.group(3) ); 
      } else {
         System.out.println("NO MATCH");
      }
   }
}

Java的正则表达式特殊语法

注意到上面例子的正则表达式中限定非数字使用(\\D*),但我们介绍正则表达式时,提到非数字用\D表示,为什么会多出一个反斜线呢?

在其他语言中,\\ 表示:我想要在正则表达式中插入一个普通的(字面上的)反斜杠,请不要给它任何特殊的意义。

在 Java 中,\\ 表示:我要插入一个正则表达式的反斜线,所以其后的字符具有特殊的意义。所以在其他语言中,一个反斜杠 \ 就足以具有转义的作用,而在 Java 中正则表达式中则需要有两个反斜杠才能被解析为其他语言中的转义作用。

Matcher 类的方法

索引方法

索引方法提供了有用的索引值,精确表明输入字符串中在哪能找到匹配:

方法说明
public int start()返回上一次匹配操作中匹配子序列的起始索引。
public int start(int group) 返回在以前的匹配操作期间,由给定组所捕获的子序列的初始索引
public int end()返回最后匹配字符之后的偏移量。
public int end(int group)返回在以前的匹配操作期间,由给定组所捕获子序列的最后字符之后的偏移量。

 例:

String regex = "\\d+";
String text = "abc 123 def";
Matcher matcher = Pattern.compile(regex).matcher(text);
if (matcher.find()) {
    System.out.println("匹配起始位置: " + matcher.start()); // 输出: 匹配起始位置: 4
    System.out.println("匹配结束位置: " + matcher.end()); // 输出: 匹配结束位置: 7
}

查找方法

查找方法用来检查输入字符串并返回一个布尔值,表示是否找到该模式:

方法说明
public boolean matches()尝试将整个输入序列与正则表达式进行匹配。
public boolean lookingAt()

 尝试从输入序列的开头开始匹配正则表达式

(匹配开头,不需要匹配整个输入序列)。

public boolean find()尝试查找与该模式匹配的输入序列的下一个子序列。
public boolean find(int start重置此匹配器,然后尝试查找匹配该模式、从指定索引开始的输入序列的下一个子序列。

 例:

matches

String regex = "\\d{3}-\\d{4}";
String text = "123-4567";
Matcher matcher = Pattern.compile(regex).matcher(text);
System.out.println(matcher.matches()); // 输出: true

lookingAt 

String regex = "\\d{3}";
String text = "123-4567";
Matcher matcher = Pattern.compile(regex).matcher(text);
System.out.println(matcher.lookingAt()); // 输出: true

 find

String regex = "\\d+";
String text = "abc 123 def 456";
Matcher matcher = Pattern.compile(regex).matcher(text);
while (matcher.find()) {
    System.out.println("找到匹配: " + matcher.group());
}
// 输出:
// 找到匹配: 123
// 找到匹配: 456
String regex = "\\d+";
String text = "abc 123 def 456";
Matcher matcher = Pattern.compile(regex).matcher(text);
if (matcher.find(5)) {
    System.out.println("找到匹配: " + matcher.group()); // 输出: 找到匹配: 23
}

替换方法

替换方法是替换输入字符串里文本的方法:

方法方法说明

public Matcher appendReplacement

(StringBuffer sb, String replacement)

将当前匹配的子序列之前的字符(从上次匹配结束到当前匹配开始)追加到 StringBuffer 中,然后将替换字符串 replacement追加到 StringBuffer 中
public StringBuffer appendTail(StringBuffer sb)

将最后一次匹配之后的剩余字符追加到 StringBuffer 中。

此方法通常与 appendReplacement结合使用,用于完成替换操作。

public String replaceAll(String replacement)将匹配的子序列全部替换为指定的字符串 replacement。
public String replaceFirst(String replacement)将第一个匹配的子序列替换为指定的字符串replacement
public static String quoteReplacement(String s)

将字符串 s 中的特殊字符(如 $ 和 \)转义,使其可以作为字面量替换字符串使用。

例:

 appendReplacement和appendTail

String regex = "\\d+";
String text = "abc 123 def 456";
Matcher matcher = Pattern.compile(regex).matcher(text);
StringBuffer sb = new StringBuffer();

while (matcher.find()) {
    matcher.appendReplacement(sb, "XXX");
}
matcher.appendTail(sb);

System.out.println(sb.toString()); // 输出: abc XXX def XXX

replaceAll

String regex = "\\d+";
String text = "abc 123 def 456";
Matcher matcher = Pattern.compile(regex).matcher(text);
String result = matcher.replaceAll("XXX");
System.out.println(result); // 输出: abc XXX def XXX

replaceFirst

String regex = "\\d+";
String text = "abc 123 def 456";
Matcher matcher = Pattern.compile(regex).matcher(text);
String result = matcher.replaceFirst("XXX");
System.out.println(result); // 输出: abc XXX def 456

PatternSyntaxException 类的方法

PatternSyntaxException 类提供了下面的方法来帮助我们查看发生了什么错误:

方法说明
public String getDescription()获取错误的描述。
public int getIndex() 获取错误的索引。
public String getPattern()获取错误的正则表达式模式。
public String getMessage()返回多行字符串,包含语法错误及其索引的描述、错误的正则表达式模式和模式中错误索引的可视化指示。

下节预告

下节开始,笔者将详细展开介绍 Java 中的方法和构造方法,看到这里的小伙伴可以投票打卡(投票有效期为7天),有疑惑可私信或评论区提出,and不妨动动发财的手点个赞吧,明天见!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值