search
HomeJavajavaTutorialJava regular multi-string matching and replacement

Java中使用也比较简单:
1. 编译正则表达式的字面值得到对应的模式Pattern对象;

2. 创建匹配给定输入与此模式的匹配器Matcher;

3. 通过匹配器对象执行操作,匹配器对象的方法很丰富,方法之间组合使用更加强大。

public static void main(String[] args) { 
    //被替换关键字的的数据源 
    Map<String,String> tokens = new HashMap<String,String>(); 
    tokens.put("cat", "Garfield"); 
    tokens.put("beverage", "coffee"); 

    //匹配类似velocity规则的字符串 
    String template = "${cat} really needs some ${beverage}."; 
    //生成匹配模式的正则表达式 
    String patternString = "\\$\\{(" + StringUtils.join(tokens.keySet(), "|") + ")\\}"; 

    Pattern pattern = Pattern.compile(patternString); 
    Matcher matcher = pattern.matcher(template); 

    //两个方法:appendReplacement, appendTail 
    StringBuffer sb = new StringBuffer(); 
    while(matcher.find()) { 
        matcher.appendReplacement(sb, tokens.get(matcher.group(1))); 
    } 
    matcher.appendTail(sb); 

    //out: Garfield really needs some coffee. 
    System.out.println(sb.toString()); 

    //对于特殊含义字符"\","$",使用Matcher.quoteReplacement消除特殊意义 
    matcher.reset(); 
    //out: cat really needs some beverage. 
    System.out.println(matcher.replaceAll("$1")); 
    //out: $1 really needs some $1. 
    System.out.println(matcher.replaceAll(Matcher.quoteReplacement("$1"))); 

    //到得邮箱的前缀名。插一句,其实验证邮箱的正则多种多样,根据自己的需求写对应的正则才是王道 
    String emailPattern = "^([a-z0-9_\\.\\-\\+]+)@([\\da-z\\.\\-]+)\\.([a-z\\.]{2,6})$"; 
    pattern = Pattern.compile(emailPattern); 
    matcher = pattern.matcher("test@qq.com"); 
    //验证是否邮箱 
    System.out.println(matcher.find()); 
    //得到@符号前的邮箱名  out: test 
    System.out.println(matcher.replaceAll("$1")); 

    //获得匹配值 
    String temp = "<meta-data android:name=\"appid\" android:value=\"joy\"></meta-data>"; 
    pattern = Pattern.compile("android:(name|value)=\"(.+?)\""); 
    matcher = pattern.matcher(temp); 
    while(matcher.find()) { 
        //out: appid, joy 
        System.out.println(matcher.group(2)); 
    } 
}

一些老是忘基础


[...] 位于括号之内的任意字符

[^...] 不在括号之中的任意字符

. 除了换行符之外的任意字符,等价于[^\n]

\w 任何单字字符, 等价于[a-zA-Z0-9]

\W 任何非单字字符,等价于[^a-zA-Z0-9]

\s 任何空白符,等价于[\ t \ n \ r \ f \ v]

\S 任何非空白符,等价于[^\ t \ n \ r \ f \ v]

\d 任何数字,等价于[0-9]

\D 除了数字之外的任何字符,等价于[^0-9]

[\b] 一个退格直接量(特例)

 

{n, m} 匹配前一项至少n次,但是不能超过m次

{n, } 匹配前一项n次,或者多次

{n} 匹配前一项恰好n次

? 匹配前一项0次或1次,也就是说前一项是可选的. 等价于 {0, 1}

+ 匹配前一项1次或多次,等价于{1,}

* 匹配前一项0次或多次.等价于{0,}

 

| 选择.匹配的要么是该符号左边的子表达式,要么它右边的子表达式

(...) 分组.将几个项目分为一个单元.这个单元可由 *、+、?和|等符号使用,而且还可以记住和这个组匹配的字符以供此后引用使用

\n 和第n个分组所匹配的字符相匹配.分组是括号中的子表达式(可能是嵌套的).分组号是从左到右计数的左括号数

 

^ 匹配的是字符的开头,在多行检索中,匹配的是一行的开头

$ 匹配的是字符的结尾,在多行检索中,匹配的是一行的结尾

\b 匹配的是一个词语的边界.简而言之就是位于字符\w 和 \w之间的位置(注意:[\b]匹配的是退格符)

\B 匹配的是非词语的边界的字符


题外话


邮箱验证,以前验证邮箱,网上搜个正则装在自己程序里面就用,其实这是不对的,不同的公司对邮箱的验证格式是不一样的,比方说163和qq邮箱注册,他们要求的格式都不一样,所以搜一个正则表达式就去套所有的邮箱格式也是不对的,符合自己的需求的正则才是正确的。

更多Java正则多字符串匹配替换相关文章请关注PHP中文网!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools