[Java] 简化正则表达式的使用

使用

RegexString.with(string).pattern(pattern).start() + 后续操作(matches,find或者是replace)

源码

package com;

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

/**
 * @author [email protected] 用于简化处理正则表达式
 */
public class RegexString {

    private String string;
    private Pattern pattern;
    private Matcher matcher;

    ////////////////////// Constructor //////////////////////

    /**
     * 正则表达式对象
     *
     * @param str
     *            初始化用的字符串
     */
    public RegexString(String str) {
        setString(Objects.requireNonNull(str));
    }

    ////////////////////// Normal Method //////////////////////

    /**
     * 设置正则表达式的pattern
     *
     * @param regex
     *            正则表达式语句
     * @return RegexString
     */
    public RegexString pattern(String regex) {
        setPattern(Pattern.compile(regex));
        return this;
    }

    /**
     * 设置正则表达式的pattern
     *
     * @param regex
     *            正则表达式语句
     * @param flags
     *            正则表达式flag值
     * @return RegexString
     */
    public RegexString pattern(String regex, int flags) {
        setPattern(Pattern.compile(regex, flags));
        return this;
    }

    /**
     * 正则表达式对象开始匹配(设置完pattern后需要自行此语句才能做后续操作)
     *
     * @return RegexString
     */
    public RegexString start() {
        setMatcher(pattern.matcher(string));
        return this;
    }

    /**
     * 进行文本替换
     *
     * @param replacement
     *            用来替换的文本
     * @return 替换后的字符串
     */
    public String replace(String replacement) {
        return getMatcher().replaceAll(replacement);
    }

    /**
     * 判断是否匹配(一次性匹配全部文本,不分步)
     *
     * @return 匹配了返回true,没有匹配返回false.
     */
    public boolean matches() {
        return getMatcher().matches();
    }

    /**
     * 判断是否匹配(分步匹配文本,请结合while循环使用)
     *
     * @return 找到了返回true,没有找到返回false.
     */
    public boolean find() {
        return getMatcher().find();
    }

    /**
     * find()操作成功后,可以通过matchString()获取匹配的字符串
     *
     * @return 匹配的字符串
     */
    public String matchString() {
        return getMatcher().group();
    }

    /**
     * find()操作成功后,可以通过matchStart()获取匹配的起始位置
     *
     * @return 匹配的起始位置
     */
    public int matchStart() {
        return getMatcher().start();
    }

    /**
     * find()操作成功后,可以通过matchEnd()获取匹配的结束位置
     *
     * @return 匹配的起始位置
     */
    public int matchEnd() {
        return getMatcher().end();
    }

    ////////////////////// Static Method //////////////////////

    /**
     * [静态方法] 便利构造器
     *
     * @param str
     *            初始化用的字符串
     * @return RegexString
     */
    public static RegexString with(String str) {
        return new RegexString(str);
    }

    ////////////////////// Getter & Setter //////////////////////

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Matcher getMatcher() {
        return matcher;
    }

    public void setMatcher(Matcher matcher) {
        this.matcher = matcher;
    }
}

示例

package com;

public class Main {

    public static void main(String args[]) {

        // 查找文本
        {
            String src = "This is my small example string which I‘m going to use for pattern matching.";
            RegexString string = RegexString.with(src).pattern("\\w+").start();
            while (string.find()) {
                System.out.println(string.matchStart() + "," + string.matchEnd() + " : " + string.matchString());
            }
        }

        // 匹配
        {
            String src = "This is my small example string which I‘m going to use for pattern matching.";
            if (RegexString.with(src).pattern("^This.+$").start().matches()) {
                System.out.println("Yes");
            }
        }

        // 替换文本
        {
            String src = "This is my small example string which I‘m going to use for pattern matching.";
            System.out.println(RegexString.with(src).pattern("\\w+").start().replace("Regex"));
        }

        // 去掉字符串首尾的空格,以及字符串中间多余的字符串
        {
            String src = "   This    is    my small example string    which  I‘m    going to    use  for  pattern  matching.     ";
            String tmp = RegexString.with(src).pattern("^\\s+|\\s+$").start().replace("");
            String des = RegexString.with(tmp).pattern("\\s+").start().replace(" ");
            System.out.println("\"" + des + "\"");
        }
    }
}
时间: 2024-08-04 04:28:11

[Java] 简化正则表达式的使用的相关文章

java常用正则表达式

java常用正则表达式 1.^\d+$ //匹配非负整数(正整数 + 0) 2.^[0-9]*[1-9][0-9]*$ //匹配正整数 3.^((-\d+) ?(0+))$ //匹配非正整数(负整数 + 0) 4.^-[0-9]*[1-9][0-9]*$ //匹配负整数 5.^-?\d+$ //匹配整数 6.^\d+(\.\d+)?$ //匹配非负浮点数(正浮点数 + 0) 7.^(([0-9]+\.[0-9]*[1-9][0-9]*) ?([0-9]*[1-9][0-9]*\.[0-9]+)

Java中用正则表达式找出数字

Java中用正则表达式找出数字 1.题目    String str = "fjd789klsd908434jk#$$%%^38488545",从中找出78990843438488545,请找到解决办法 2.实现源码 /** * */ package com.you.model; /** * @author YouHaidong * */ public class FindNumber { /** * 字符串str */ public static String str = "

java中 正则表达式的使用

推荐使用第一种 第一种: //对接收的文件名的合法性进行验证 String fileName="127.0.0.1_01_20140428165022174.jpg"; String regEx = "\\b.+_\\d+_\\d{17}\\b"; //正则表达式 Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(fileName); if(!m.find()){ SysLog.logger.erro

Java中正则表达式的使用(常用的方法)

这两天回想了一下正则表达式的使用,顺便就总结了一下java的javascript中使用正则表达式的用法,需要看javascript中使用正则的朋友可以看我的另一篇总结,下面我就简单的介绍一下java中正则表达式的使用.方便自己以后查询使用,也希望能帮助到大家.===欢迎指正=== 在JDK1.3及之前的JDK版本中并没有包含正则表达式的类,如果要在Java中使用正则表达式必须使用第三方提供的正则表达式库.从JDK1.4开始提供了支持正则表达式API,它们位于java.util.regex包中.

Java对正则表达式的支持(一)

Java对正则表达式的支持主要体现在String.Pattern.Matcher和Scanner类. 1.Pattern.Matcher 先看一个Pattern和Matcher类使用正则表达式的例子. public class PatternTest { public static void main(String [ ] args) { String testString = "abcabcabcdefabc"; String [] regexs = new String []{&q

Java使用正则表达式取网页中的一段内容(以取Js方法为例)

关于正则表达式: 表1.常用的元字符 代码 说明 . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 \s 匹配任意的空白符 \d 匹配数字 \b 匹配单词的开始或结束 ^ 匹配字符串的开始 $ 匹配字符串的结束 表2.常用的限定符 代码/语法 说明 * 重复零次或更多次 + 重复一次或更多次 ? 重复零次或一次 {n} 重复n次 {n,} 重复n次或更多次 {n,m} 重复n到m次 表3.常用的反义代码 代码/语法 说明 \W 匹配任意不是字母,数字,下划线,汉字的字符 \S

1000行代码徒手写正则表达式引擎【1】--JAVA中正则表达式的使用

简介: 本文是系列博客的第一篇,主要讲解和分析正则表达式规则以及JAVA中原生正则表达式引擎的使用.在后续的文章中会涉及基于NFA的正则表达式引擎内部的工作原理,并在此基础上用1000行左右的JAVA代码,实现一个支持常用功能的正则表达式引擎.它支持贪婪匹配和懒惰匹配:支持零宽度字符(如"\b", "\B"):支持常用字符集(如"\d", "\s"等):支持自定义字符集("[a-f]","[^b-

Java常用正则表达式验证工具类RegexUtils.java

原文:Java常用正则表达式验证工具类RegexUtils.java 源代码下载地址:http://www.zuidaima.com/share/1550463379442688.htm Java 表单注册常用正则表达式验证工具类,常用正则表达式大集合. 1. 电话号码 2. 邮编 3. QQ 4. E-mail 5. 手机号码 6. URL 7. 是否为数字 8. 是否为中文 9. 身份证 10. 域名 11. IP .... 常用验证应有尽有! 这的确是您从事 web 开发,服务器端表单验证

Java 常用正则表达式搜集ing

MAC地址: ^[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}$ IPv4地址: \\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25