java正则表达式提取字符串中指定的数据

什么是正则表达式?

正则表达式是一种用来描述、匹配和操作字符串的强大工具。它可以用于验证输入的字符串、提取特定格式的字符串、替换字符串中的特定部分等操作。

String 类里也提供了如下几个特殊的方法。

//判断该字符串是否匹配指定的正则表达式。
boolean matches(String regex)

//将该字符串中所有匹配 regex 的子串替换成replacement。 
String replaceAll(String regex, String replacement)

//将该字符串中第一个匹配 regex 的子串替换成 replacement。
String replaceFirst(String regex, String replacement)

//以 regex 作为分隔符,把该字符串分割成多个子串。
String[] split(String regex)

测试案例

package com.example.demo.aaa;

import java.util.regex.*;
 
public class RegexDemo {
    public static void main(String[] args) {
        String input = "Hello, 123456!我是一个好人a543,qq号是103456789";
        String pattern = "\\d+";
 
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(input);
 
        while (m.find()) {
            System.err.println("match number:" + m.group());
        }
    }
}

输出:
match number:123456
match number:543
match number:103456789

String input = "The sales increased by 25% last month.52 sun 0.52 main 30% or 35%";
        String regex = "\\d+%";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            String percentage = matcher.group();
            System.err.println("Percentage: " + percentage);
        }

输出:
Percentage: 25%
Percentage: 30%
Percentage: 35%

代码解析:

首先定义了一个输入字符串input和一个正则表达式模式pattern
使用Pattern.compile()方法将正则表达式编译成一个Pattern对象。
使用p.matcher(input)方法创建一个Matcher对象,用于进行匹配。
使用m.find()方法循环查找输入字符串中与正则表达式匹配的部分。
使用m.group()方法获取匹配到的部分。
 

你可能感兴趣的:(java,开发语言)