Home Java javaTutorial Java regular expression method to extract characters

Java regular expression method to extract characters

Jan 22, 2017 pm 02:29 PM

正好遇到一个需求需要将字符串中特定的字符全部提取出来,这个如果是按常规的字符串处理的话非常的繁琐。于是想到用正则表达式来完成。项目需求是这样的:需要提取车牌号中最后一个数字,比如说:苏A7865提取5,苏A876X提取6

实现方法:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String s = "A876X";
// 把要匹配的字符串写成正则表达式,然后要提取的字符使用括号括起来
// 在这里,我们要提取最后一个数字,正则规则就是“一个数字加上大于等于0个非数字再加上结束符”
Pattern pattern = Pattern.compile("(\\d)[^\\d]*$");
Matcher matcher = pattern.matcher(s);
if(matcher.find())
System.out.println(matcher.group(1));
}
}
Copy after login

关于Matcher 中的几个方法说明:

Mathcer.start()/ Matcher.end()/ Matcher.group()
当使用matches(),lookingAt(),find()执行匹配操作后,就可以利用以上三个方法得到更详细的信息.
start()返回匹配到的子字符串在字符串中的索引位置.
end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
group()返回匹配到的子字符串

Java代码示例:

Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“aaa2223bb”);
m.find();//匹配2223
m.start();//返回3
m.end();//返回7,返回的是2223后的索引号
m.group();//返回2223
Mathcer m2=p.matcher(“2223bb”);
m2.lookingAt(); //匹配2223
m2.start(); //返回0,由于lookingAt()只能匹配前面的字符串,所以当使用lookingAt()匹配时,start()方法总是返回0
m2.end(); //返回4
m2.group(); //返回2223
Matcher m3=p.matcher(“2223”); //如果Matcher m3=p.matcher(“2223bb”); 那么下面的方法出错,因为不匹配返回false
m3.matches(); //匹配整个字符串
m3.start(); //返回0
m3.end(); //返回3,原因相信大家也清楚了,因为matches()需要匹配所有字符串
m3.group(); //返回2223
Copy after login

说了这么多,相信大家都明白了以上几个方法的使用,该说说正则表达式的分组在java中是怎么使用的.
start(),end(),group()均有一个重载方法它们是start(int i),end(int i),group(int i)专用于分组操作,Mathcer类还有一个groupCount()用于返回有多少组.

Java代码示例:

Pattern p=Pattern.compile(“([a-z]+)(\d+)”);
Matcher m=p.matcher(“aaa2223bb”);
m.find(); //匹配aaa2223
m.groupCount(); //返回2,因为有2组
m.start(1); //返回0 返回第一组匹配到的子字符串在字符串中的索引号
m.start(2); //返回3
m.end(1); //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置.
m.end(2); //返回7
m.group(1); //返回aaa,返回第一组匹配到的子字符串
m.group(2); //返回2223,返回第二组匹配到的子字符串
Copy after login

现在我们使用一下稍微高级点的正则匹配操作,例如有一段文本,里面有很多数字,而且这些数字是分开的,我们现在要将文本中所有数字都取出来,利用java的正则操作是那么的简单.

Java代码示例:

Pattern p=Pattern.compile(“\d+”);
Matcher m=p.matcher(“我的QQ是:456456 我的电话是:0532214 我的邮箱是:aaa123@aaa.com”);
while(m.find()) {
System.out.println(m.group());
}
Copy after login

输出:

456456
0532214
123

如将以上while()循环替换成

while(m.find()) {
System.out.println(m.group());
System.out.print(“start:”+m.start());
System.out.println(” end:”+m.end());
}
Copy after login

则输出:

456456 
start:6 end:12 
0532214 
start:19 end:26 
123 
start:36 end:39

现在大家应该知道,每次执行匹配操作后start(),end(),group()三个方法的值都会改变,改变成匹配到的子字符串的信息,以及它们的重载方法,也会改变成相应的信息. 

注意:只有当匹配操作成功,才可以使用start(),end(),group()三个方法,否则会抛出java.lang.IllegalStateException,也就是当matches(),lookingAt(),find()其中任意一个方法返回true时,才可以使用。

以上内容给介绍了Java正则表达式提取字符的方法实例,希望对大家有所帮助。

更多Java正则表达式提取字符的方法实例相关文章请关注PHP中文网!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

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...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? Apr 19, 2025 pm 01:51 PM

Discussing the hierarchical architecture in back-end development. In back-end development, hierarchical architecture is a common design pattern, usually including controller, service and dao three layers...

Ultimate consistency in distributed systems: how to apply and how to compensate for data inconsistencies? Ultimate consistency in distributed systems: how to apply and how to compensate for data inconsistencies? Apr 19, 2025 pm 02:24 PM

Exploring the application of ultimate consistency in distributed systems Distributed transaction processing has always been a problem in distributed system architecture. To solve the problem...

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...

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

How to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? How to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? Apr 19, 2025 pm 02:30 PM

How to use OAuth2.0's access_token to achieve control of interface access permissions? In the application of OAuth2.0, how to ensure that the...

See all articles