Java中正则表达式相关的类都在java.util.regex之内,一般来说,主要用到的是这两个类:java.util.regex.Pattern和java.util.regex.Matcher。Pattern对应正则表达式,一个Pattern与一个String对象关联,生成一个Matcher,它对应Pattern在String中的一次匹配; 调用Matcher对象的find()方法,Matcher对象就会更新为下一次匹配的匹配信息。示例:
Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-]]d{2}"); String string = "2010-12-20 2011-02-14"; Matcher matcher = pattern.matcher(string); while(matcher.find()) { System.out.println(matcher.group(0)); }
Pattern
Pattern是Java语言中的正则表达式对象。要使用正则表达式,首先必须从字符串“编译”出Pattern对象,这需要用到Pattern.compile(String regex)方法。
Pattern pattern = Pattern.compile("a.b+");
如果要指定匹配模式,可以在表达式中使用(?modifier)修饰符指定,也可以使用预定义常量。下面的两个Pattern对象的生成方法不同,结果却是等价的。
Pattern pattern = Pattern.compile("(?i)a.b+"); Pattern pattern = Pattern.compile("a.b+",Pattern.CASE_INSENSITIVE);
如果要同时指定多种模式,可以连写模式修饰符,也可以直接用|运算符将预定义常量连接起来,以下两个Pattern对象也是等价的。
Pattern pattern = Pattern.compile("(?is)a.b+"); Pattern pattern = Pattern.compile("a.b+",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
下面介绍Pattern的主要成员方法:
1. static boolean matches(String regex.CharSequence input)
这个方法可以检验字符串input能否由正则表达式regex匹配,因为是静态方法,所以不需要编译生成各个对象,方便随手使用。要注意的是,它检验的是“整个字符串能否由表达式匹配”,而不是“表达式能否在字符串中找到匹配”。你可以认为regex的首尾自动加上了匹配字符串起始和结束位置的锚点 \A和\z 。
Pattern.matches("\\d{6}","a123456"); //false Pattern.matches("\\d{6}","123456"); //true
2. String[] split(CharSequence text)
通常,Pattern对象需要配合下面将要介绍的Matcher一起完成正则操作。如果只用正则表达式来切分字符串,只用Pattern的这个方法也可以。
这个方法接收的参数类型是CharSequence它可能有点陌生,其实它是String的父类,其他子类还有CharBuffer,StringBuffer,StringBuilder,因而可以应对常见的各种表示“字符串”的类。下面的代码仅以String为例:
String s = "2010-12-20"; Pattern pattern = Pattern.compile("\\s+"); for(String part : pattern.split(s)){ System.out.println(part); }
3. String[] split(CharSequence text,int limit)
这个方法与上面的方法很相似,只是多了一个参数limit,它用来限定返回的String数组的最大长度。也就是说,它规定了字符串至多只能“切”limit-1次。如果不需要对字符串比较大,进行尽可能多的切分,使用这个方法。
String s = " 2010-12-20 "; Pattern pattern = Pattern.compile("\\s+"); for(String part : Pattern.split(s,2)){ System.out.println(part); }
既然limit是一个int类型,那么它自然可以设定为各种值,下表总结了limit在各个取值区间对结果的影响(未指定limit时,最终返回包含n个元素的数组,实际能切分的次数是 n-1 ):
取值 |
结果 |
limit | 等于未设定limit时,保留末尾的空字符串 |
limit = 0 |
等于未设定limit时,切分n-1次,忽略末尾的空字符串 |
0 | 返回数组包含limit个元素,切分limit-1次,最后一个元素是第limit-1次切分后,右侧剩下的所有文本 |
limit >= n |
等于未指定limit时 |
4. static String quote(String text)
这个方法用来取消字符串text中所有转义字符的特殊含义,实质就是在字符串首尾添加 \Q 和 \E。通常,如果需要把某个字符串作为没有任何特殊意义的正则表达式(比如从外界读入的字符串,用在某个复杂的正则表达式中),就可以使用这个方法:
"aacb".matches("a*.b"); //true "a*.b".matches("a*.b"); //false "a*.b".matches("a*.b"); //false "a*.b".matches(Pattern.quote("a*.b")); //true
Matcher
Matcher可以理解为“某次具体匹配的结果对象”:把编译好的Pattern对象“应用”到某个String对象上,就获得了作为“本次匹配结果”的Matcher对象。之后,就可以通过它获得关于匹配的信息。
Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}"); Matcher matcher = pattern.matcher("2010-12-20 2011-02-14"); while(matcher.find()){ System.out.println(matcher.group()); }
对编译好的Pattern对象调用matcher(String text)方法,传入要匹配的字符串text,就得到了Matcher对象,每次调用一次find()方法,如果返回true,就表示“找到一个匹配”,此时可以通过下面的若干方法获得关于本次匹配的信息。
1. String group(int n)
返回当前匹配中第n对捕获括号捕获的文本,如果n为0,则取匹配的全部内容;如果n小于0或者大于最大分组编号数,则报错。
2. String group()
返回当前匹配的全部文本,相当于group(0)。
3. int groupCount()
返回此Matcher对应Pattern对象中包含的捕获分组数目,编号为0的默认分组不计在内。
4. int start(n)
返回当前匹配中第n对捕获括号匹配的文本在原字符串中的起始位置。
5. int start()
返回当前匹配的文本在原字符串中的起始位置,相当于start(0)。
6. int end(n)
返回当前匹配中第n对捕获括号匹配的文本在原字符串中的结束位置。
7. int end()
返回当前匹配的文本在原字符串中的结果位置,相当于end(0)。
8. String replaceAll(String replacement)
如果进行正则表达式替换,一般用到的是Matcher的replaceAll()方法,它会将原有文本中正则表达式能匹配的所有文本替换为replaceement字符串。
String
许多时候只需要临时使用某个正则表达式,而不需要重复使用,这时候每次都生成Pattern对象和Matcher对象再操作显得很烦琐。所以,Java的String类提供了正则表达式操作的静态成员方法,只需要String对象就可以执行正则表达式操作。
1. boolean matches(String regex)
这个方法判断当前的string对象能否由正则表达式regex匹配。请注意,这里的“匹配”指的并不是regex能否在String内找到匹配,而是指regex匹配整个String对象,因此非常适合用来做数据校验。
"123456".matches("\\d{6}"); //true "a123456".matches("\\d{6}"); //true
2. String replaceFirst(String regex,String replacement)
这个方法用来替换正则表达式regex在字符串中第一次能匹配的文本,可以在replacement字符串中用$num引用regex中对应捕获分组匹配的文本。
"2010-12-20 2011-02-14".replaceFirst("(\\d{4})-(\\d{2})-(\\d{2})","$2/$3/$1");
3. String replaceAll(String regex,String replacement)
这个方法用来进行所有的替换,它的结果等同于Matcher类的replaceAll()方法,replacement字符串中也可以用$num的表示法引用regex中对应捕获分组匹配的文本。
"2010-12-20 2011-02-14".replaceAll("(\\d{4})-(\\d{2})-(\\d{2})","$2/$3/$1");
4. String[] split(String regex)
这个方法等价于Pattern中对应的split()方法,此处不再赘述。
5. String[] split(String regex,int limit)
这个方法等价于Pattern中对应的split()方法,此处不再赘述。
The above is the detailed content of Detailed explanation of Java regular expression API. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
