Java正则表达式总结

基础

相对其他语言,Java对反斜线\有不同的处理。在其他语言中,\\表示“在正则表达式中插入普通的反斜线,所以不要给他任何特殊意义”,而在Java中,\\表示“插入一个正则表达式的反斜线,所以后面的字符具有特殊意义”。例如,Java中如果表示一个数字,那么正则表达式是\\d,而其他语言则是\d。

String中的正则表达式

String中有3个方法可以使用正则表达式,分别是

//判断字符串是否匹配正则表达式,匹配返回true,不然返回false
boolean matches(String regex)

//用给定的正则表达式切割字符串,注意与正则表达式匹配的部分,在最终结果中都不存在了
String[] split(String regex)
//限定切割次数
String[] split(String regex, int limit)

//替换所有匹配到的字符串
String replaceAll(String regex, String replacement)
//替换掉第一个匹配到的字符串
String replaceFirst(String regex, String replacement)

Pattern和Matcher

导入java.util.regex,然后用static Pattern.compile()方法来编译正则表达式。他会根据String类型的正则表达式生成一个Pattern对象,接下来把想要检索的字符串传入Pattern对象的matcher()方法,matcher()方法会生成一个Matcher对象,之后就可以调用Matcher对象里面的方法匹配。例如:

Pattern p = Pattern.compile("a*b");   //编译正则表达式
Matcher m = p.matcher("aaaaab");   //要检索的字符串
/**
*Attempts to match the entire region against the pattern.
*If the match succeeds then more information can be obtained via the start, end, and group methods.
*/
boolean b = m.matches();

下面的代码跟上面实现了同样功能

boolean b = Pattern.matches("a*b", "aaaaab");

CharSequence

接口CharSequence从CharBuffer、String、StringBuilder、StringBuffer类中抽象出了字符序列的一般化定义:

interface CharSequence {
  charAt(int i);
  length();
  subSequence(int start, int end);
  toString();
}

因此下面Pattern和Matcher的一些方法是以CharSequence对象作为参数。

Pattern

Patten类的定义

public final class Pattern
extends Object
implements Serializable

Pattern对象表示编译后的正则表达式。由于Pattern是final的,所以是不可变的,线程安全的。

一些常用的方法:

编译正则表达式
public static Pattern compile(String regex)
public static Pattern compile(String regex, int flags)

flags表示编译标记,一共有9种,他们都是final static int类型的,分别是

  • Pattern.CANON_EQ
  • Pattern.CASE_INSENSITIVE(?i)
  • Pattern.COMMENTS(?x)
  • Pattern.DOTALL(?s)
  • Pattern.LITERAL
  • Pattern.MULTILINE(?m)
  • Pattern.UNICODE_CASE(?u)
  • Pattern.UNICODE_CHARACTER_CLASS(?U)
  • Pattern.UNIX_LINES(?d)
    后面括号字符表示当插入到字符串里面会被识别到而启动这种模式(注意:可以插入到任何位置)。例如:
    Matcher m = Pattern.compile("(?m)(\\\\S+)\\\\s+((\\\\S+)\\\\s+(\\\\S+))$").matcher("I love Java");
    等于
    Matcher m = Pattern.compile("(\\\\S+)\\\\s+((\\\\S+)\\\\s+(\\\\S+))$", Pattern.MULTILINE).matcher("I love Java");
生成Matcher对象
public Matcher matcher(CharSequence input)
匹配操作
public static boolean matches(String regex, CharSequence input)
public String[] split(CharSequence input, int limit)
public String[] split(CharSequence input)

Matcher

Matcher类的定义

public final class Matcher
extends Object
implements MatchResult

Matcher是通过解释Pattern而在CharSequence上执行匹配操作的一个引擎。通过调用Pattern.matcher()方法可以生产一个Matcher对象。创建之后,Matcher对象就可以执行三种匹配操作:

  • The matches method attempts to match the entire input sequence against the pattern.(只有在整个输入都匹配正则表达式时才会返回true)
  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.(字符串开始处匹配正则表达式就返回true,否则返回false)
  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

这三个方法都返回boolean标志表明匹配成功或者失败。如果成功了就可以调用其他方法进行各种操作。

一些常用的方法:

匹配操作
/**
*Attempts to match the entire region against the pattern.
*If the match succeeds then more information can be obtained via the start, end, and group methods.
*
*Returns:
*true if, and only if, the entire region sequence matches this matcher's pattern
*/
public boolean matches()
/**
*Attempts to find the next subsequence of the input sequence that matches the pattern.
*This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
*
*If the match succeeds then more information can be obtained via the start, end, and group methods.
*
*Returns:
*true if, and only if, a subsequence of the input sequence matches this matcher's pattern
*/
public boolean find()
public boolean find(int start)
/**
*Attempts to match the input sequence, starting at the beginning of the region, against the pattern.
*Like the matches method, this method always starts at the beginning of the region; unlike that method, it does not require that the entire region be matched.
*
*If the match succeeds then more information can be obtained via the start, end, and group methods.
*
*Returns:
*true if, and only if, a prefix of the input sequence matches this matcher's pattern
*/
public boolean lookingAt()
组(Groups)

组是用括号划分的正则表达式,可以根据组的编号来引用某个组。组号为0表示整个表达式,组号1表示被第一个括号括起的组,以此类推。例如:
A(B(C))D
中有3个组:组0是ABCD,组1是BC,组2是C。

//返回该匹配器的模式中的分组数目,第0组不包括在内。在group、start和end方法中可以使用小于此数目的数字作为numth参数
public int groupCount()

//返回前一次匹配(例如find())操作的第0组(整个匹配)
public String group()
//返回编号为num的捕获型括号匹配的内容,如果匹配成功,但是指定的组没有匹配输入字符串的任何部分,则将会返回null
public String group(int group)
public String group(String name)

//返回这个匹配起点的绝对偏移值,start()就等于start(0)
public int start()
//返回编号为第group的捕获型括号所匹配文本的起点在目标字符串中的绝对偏移值——即从目标字符串起始位置开始计算的偏移值。如果匹配型括号没有参与匹配,则返回-1
public int start(int group)

public int end()
//放回在前一次匹配操作中寻找到的组的最后一个字符索引加一的值
public int end(int group)
查找与替换
public String replaceAll(String replacement)
public String replaceFirst(String replacement)

public static String quoteReplacement(String s)
设置与修改的方法
  • MatchResult对象
//返回的MatchResult对象封装了当前匹配的信息。
public MatchResult toMatchResult()
  • Pattern对象
//更改为新的Pattern对象
public Matcher usePattern(Pattern newPattern)
//返回目前所用的Pattern对象
public Pattern pattern()
  • 目标字符串(或其他CharSequence对象)
//重置回原来整个字符串
public Matcher reset()
//设置新的字符串
public Matcher reset(CharSequence input)
  • 目标字符串的检索范围
//设置新的字符检索范围
public Matcher region(int start, int end)
//返回当前字符检索范围起始
public int regionStart()
//返回当前字符检索范围结束
public int regionEnd()
  • anchoring bounds标志位
public Matcher useAnchoringBounds(boolean b)
public boolean hasAnchoringBounds()
  • transparent bounds标志位
public Matcher useTransparentBounds(boolean b)
public boolean hasTransparentBounds()
只读属性
  • 目标字符串中的match pointer或current pointer,用于支持“寻找下一个匹配”的操作。
  • 目标字符串的append pointer,在查找-替换操作中,复制未匹配的文本部分时使用。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容

  • Java的正则表达式讲解:(为了能看清,本文正则表达式用中文的句号代替英文句点) 英文句点符号:匹配单个任意字符。...
    红姑娘阅读 4,217评论 0 2
  • 正则表达式描述的是一种规则,符合这种限定规则的字符串我们认为它某种满足条件的,是我们所需的。在正则表达式中,主要有...
    Single_YAM阅读 702评论 0 4
  • 三年前的二三月份,那是头一次来成都,没有雾霾,街道干净,学生时代的我们,没有工作压力,那时真的叫生活惬意巴适。当时...
    孤远阅读 248评论 0 0
  • 本人小白,初学java,无意中接触到hihocode,看到上面有题目从简到难,手痒故一试。奈何水平有限只能从最简单...
    迈巴赫棉拖阅读 723评论 0 0
  • 推销,无处不在。当老板有任务时,你总想第一时间去承担;当孩子的老师交待要做小椅子时,你巴不得自己就是木工马上给做两...
    田田教练阅读 169评论 0 1