Java正则表达式工具类实例分享

2025-01-02 05:16:27   小编

Java正则表达式工具类实例分享

在Java编程中,正则表达式是一种强大的文本处理工具。它可以用于字符串的匹配、查找、替换等操作。为了更方便地使用正则表达式,我们可以创建一个工具类来封装常用的正则表达式操作方法。下面就来分享一个Java正则表达式工具类的实例。

创建一个名为RegexUtils的工具类。在这个类中,我们可以定义一些静态方法来实现不同的功能。

例如,定义一个方法用于验证手机号码是否合法。手机号码的正则表达式可以表示为:^1[3-9]\d{9}$ 。代码如下:

public class RegexUtils {
    public static boolean isMobile(String mobile) {
        String regex = "^1[3-9]\\d{9}$";
        return mobile.matches(regex);
    }
}

接着,我们可以再定义一个方法用于提取字符串中的数字。正则表达式可以使用\d+来匹配一个或多个数字。代码如下:

public static List<String> extractNumbers(String text) {
    List<String> numbers = new ArrayList<>();
    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        numbers.add(matcher.group());
    }
    return numbers;
}

除了上述功能,我们还可以实现替换字符串中符合正则表达式的部分。比如,将字符串中的所有空格替换为下划线。代码如下:

public static String replaceSpaces(String text) {
    String regex = "\\s";
    return text.replaceAll(regex, "_");
}

在实际应用中,我们可以在其他类中直接调用RegexUtils类中的方法。例如:

public class Main {
    public static void main(String[] args) {
        String mobile = "13812345678";
        System.out.println(RegexUtils.isMobile(mobile));

        String text = "abc 123 def 456";
        List<String> numbers = RegexUtils.extractNumbers(text);
        System.out.println(numbers);

        String replacedText = RegexUtils.replaceSpaces(text);
        System.out.println(replacedText);
    }
}

通过创建这样一个正则表达式工具类,我们可以更方便地在Java项目中使用正则表达式进行各种文本处理操作,提高代码的可读性和可维护性。

TAGS: 正则表达式 实例分享 Java 工具类

欢迎使用万千站长工具!

Welcome to www.zzTool.com