java语言的语法(Java 正则表达式详解)java基础 / Java语法结构详解...

wufei123 发布于 2024-06-12 阅读(7)

Java 提供了功能强大的正则表达式API,在java.util.regex 包下本教程介绍如何使用正则表达式API正则表达式一个正则表达式是一个用于文本搜索的文本模式换句话说,在文本中搜索出现的模式例如,你可以用正则表达式搜索网页中的邮箱地址或超链接。

正则表达式示例下面是一个简单的Java正则表达式的例子,用于在文本中搜索 http://String text    =        "This is the text to be searched " +        "for occurrences of the http:// pattern."; String pattern = ".*http://.*"; boolean matches = Pattern.matches(pattern, text); System.out.println("matches = " + matches);

示例代码实际上没有检测找到的 http:// 是否是一个合法超链接的一部分,如包含域名和后缀(.com,.net 等等)代码只是简单的查找字符串 http:// 是否出现Java6 中关于正则表达式的API。

本教程介绍了Java6 中关于正则表达式的APIPattern (java.util.regex.Pattern)类 java.util.regex.Pattern 简称 Pattern, 是Java正则表达式API中的主要入口,无论何时,需要使用正则表达式,从Pattern 类开始。

Pattern.matches()检查一个正则表达式的模式是否匹配一段文本的最直接方法是调用静态方法Pattern.matches(),示例如下:String text    =        "This is the text to be searched " +        "for occurrences of the pattern."; String pattern = ".*is.*"; boolean matches = Pattern.matches(pattern, text); System.out.println("matches = " + matches);

上面代码在变量 text 中查找单词 “is” 是否出现,允许”is” 前后包含 0或多个字符(由 .* 指定)Pattern.matches() 方法适用于检查 一个模式在一个文本中出现一次的情况,或适用于Pattern类的默认设置。

如果需要匹配多次出现,甚至输出不同的匹配文本,或者只是需要非默认设置需要通过Pattern.compile() 方法得到一个Pattern 实例Pattern.compile()如果需要匹配一个正则表达式在文本中多次出现,需要通过Pattern.compile() 方法创建一个Pattern对象。

示例如下String text    =        "This is the text to be searched " +        "for occurrences of the http:// pattern."; String patternString = ".*http://.*"; Pattern pattern = Pattern.compile(patternString);

可以在Compile 方法中,指定一个特殊标志:Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);Pattern 类包含多个标志(int 类型),这些标志可以控制Pattern 匹配模式的方式。

上面代码中的标志使模式匹配是忽略大小写Pattern.matcher()一旦获得了Pattern对象,接着可以获得Matcher对象Matcher 示例用于匹配文本中的模式.示例如下Matcher matcher = pattern.matcher(text);。

Matcher类有一个matches()方法,可以检查文本是否匹配模式以下是关于Matcher的一个完整例子String text    =        "This is the text to be searched " +        "for occurrences of the http:// pattern."; String patternString = ".*http://.*"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(text); boolean matches = matcher.matches(); System.out.println("matches = " + matches);。

Pattern.split()Pattern 类的 split()方法,可以用正则表达式作为分隔符,把文本分割为String类型的数组示例:String text = "A sep Text sep With sep Many sep Separators"; String patternString = "sep"; Pattern pattern = Pattern.compile(patternString); String[] split = pattern.split(text); System.out.println("split.length = " + split.length); for(String element : split){    System.out.println("element = " + element); }。

上例中把text 文本分割为一个包含5个字符串的数组Pattern.pattern()Pattern 类的 pattern 返回用于创建Pattern 对象的正则表达式,示例:String patternString = "sep"; Pattern pattern = Pattern.compile(patternString); String pattern2 = pattern.pattern();。

上面代码中 pattern2 值为sep ,与patternString 变量相同Matcher (java.util.regex.Matcher)java.util.regex.Matcher 类用于匹配一段文本中多次出现一个正则表达式,Matcher 也适用于多文本中匹配同一个正则表达式。

Matcher 有很多有用的方法,详细请参考官方JavaDoc这里只介绍核心方法以下代码演示如何使用MatcherString text    =        "This is the text to be searched " +        "for occurrences of the http:// pattern."; String patternString = ".*http://.*"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(text); boolean matches = matcher.matches();。

首先创建一个Pattern,然后得到Matcher ,调用matches() 方法,返回true 表示模式匹配,返回false表示不匹配可以用Matcher 做更多的事创建Matcher通过Pattern 的matcher() 方法创建一个Matcher。

String text    =        "This is the text to be searched " +        "for occurrences of the http:// pattern."; String patternString = ".*http://.*"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(text);

matches()Matcher 类的 matches() 方法用于在文本中匹配正则表达式boolean matches = matcher.matches();如果文本匹配正则表达式,matches() 方法返回true。

否则返回falsematches() 方法不能用于查找正则表达式多次出现如果需要,请使用find(), start() 和 end() 方法lookingAt()lookingAt() 与matches() 方法类似,最大的不同是,lookingAt()方法对文本的开头匹配正则表达式;而。

matches() 对整个文本匹配正则表达式换句话说,如果正则表达式匹配文本开头而不匹配整个文本,lookingAt() 返回true,而matches() 返回false 示例:String text    =        "This is the text to be searched " +        "for occurrences of the http:// pattern."; String patternString = "This is the"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(text); System.out.println("lookingAt = " + matcher.lookingAt()); System.out.println("matches   = " + matcher.matches());。

上面的例子分别对文本开头和整个文本匹配正则表达式 “this is the”. 匹配文本开头的方法(lookingAt()) 返回true对整个文本匹配正则表达式的方法 (matches()) 返回false,因为 整个文本包含多余的字符,而 正则表达式要求文本精确匹配”this is the”,前后又不能有额外字符。

find() + start() + end()find() 方法用于在文本中查找出现的正则表达式,文本是创建Matcher时,通过 Pattern.matcher(text) 方法传入的如果在文本中多次匹配,find() 方法返回第一个,之后每次调用 find() 都会返回下一个。

start() 和 end() 返回每次匹配的字串在整个文本中的开始和结束位置实际上, end() 返回的是字符串末尾的后一位,这样,可以在把 start() 和 end() 的返回值直接用在String.substring() 里。

String text    =        "This is the text which is to be searched " +        "for occurrences of the word is."; String patternString = "is"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(text); int count = 0; while(matcher.find()) {    count++;    System.out.println("found: " + count + " : "  + matcher.start() + " - " + matcher.end()); }

这个例子在文本中找到模式 “is” 4次,输出如下:found: 1 : 2 - 4 found: 2 : 5 - 7 found: 3 : 23 - 25 found: 4 : 70 - 72reset()

reset() 方法会重置Matcher 内部的 匹配状态当find() 方法开始匹配时,Matcher 内部会记录截至当前查找的距离调用 reset() 会重新从文本开头查找也可以调用 reset(CharSequence) 方法. 这个方法重置Matcher,同时把一个新的字符串作为参数传入,用于代替创建 Matcher 的原始字符串。

group()假设想在一个文本中查找URL链接,并且想把找到的链接提取出来当然可以通过 start()和 end()方法完成但是用group()方法更容易些分组在正则表达式中用括号表示,例如:(John)。

此正则表达式匹配John, 括号不属于要匹配的文本括号定义了一个分组当正则表达式匹配到文本后,可以访问分组内的部分使用group(int groupNo) 方法访问一个分组一个正则表达式可以有多个分组每个分组由一对括号标记。

想要访问正则表达式中某分组匹配的文本,可以把分组编号传入 group(int groupNo)方法group(0) 表示整个正则表达式,要获得一个有括号标记的分组,分组编号应该从1开始计算String text    =  "John writes about this, and John writes about that," +                        " and John writes about everything. "  ; String patternString1 = "(John)"; Pattern pattern = Pattern.compile(patternString1); Matcher matcher = pattern.matcher(text); while(matcher.find()) {    System.out.println("found: " + matcher.group(1)); }。

以上代码在文本中搜索单词John.从每个匹配文本中,提取分组1,就是由括号标记的部分输出如下found: John found: John found: John多分组上面提到,一个正则表达式可以有多个分组,例如:。

(John) (.+?)这个表达式匹配文本”John” 后跟一个空格,然后跟1个或多个字符,最后跟一个空格你可能看不到最后的空格这个表达式包括一些字符有特别意义字符 点 . 表示任意字符 字符 + 表示出现一个或多个,和. 在一起表示 任何字符,出现一次或多次。

字符? 表示 匹配尽可能短的文本完整代码如下String text    =          "John writes about this, and John Doe writes about that," +                  " and John Wayne writes about everything."        ; String patternString1 = "(John) (.+?) "; Pattern pattern = Pattern.compile(patternString1); Matcher matcher = pattern.matcher(text); while(matcher.find()) {    System.out.println("found: " + matcher.group(1) +                       " "       + matcher.group(2)); }

注意代码中引用分组的方式代码输出如下found: John writes found: John Doe found: John Wayne嵌套分组在正则表达式中分组可以嵌套分组,例如((John) (.+?))。

这是之前的例子,现在放在一个大分组里.(表达式末尾有一个空格)当遇到嵌套分组时, 分组编号是由左括号的顺序确定的上例中,分组1 是那个大分组分组2 是包括John的分组,分组3 是包括 .+? 的分组当需要通过groups(int groupNo) 引用分组时,了解这些非常重要。

以下代码演示如何使用嵌套分组String text    =          "John writes about this, and John Doe writes about that," +                  " and John Wayne writes about everything."        ; String patternString1 = "((John) (.+?)) "; Pattern pattern = Pattern.compile(patternString1); Matcher matcher = pattern.matcher(text); while(matcher.find()) {    System.out.println("found:   "); }

输出如下found: found: found:replaceAll() + replaceFirst()replaceAll() 和 replaceFirst() 方法可以用于替换Matcher搜索字符串中的一部分。

replaceAll() 方法替换全部匹配的正则表达式,replaceFirst() 只替换第一个匹配的在处理之前,Matcher 会先重置所以这里的匹配表达式从文本开头开始计算示例如下String text    =          "John writes about this, and John Doe writes about that," +                  " and John Wayne writes about everything."        ; String patternString1 = "((John) (.+?)) "; Pattern pattern = Pattern.compile(patternString1); Matcher matcher = pattern.matcher(text); String replaceAll = matcher.replaceAll("Joe Blocks "); System.out.println("replaceAll   = " + replaceAll); String replaceFirst = matcher.replaceFirst("Joe Blocks "); System.out.println("replaceFirst = " + replaceFirst);。

输出如下replaceAll = Joe Blocks about this, and Joe Blocks writes about that, and Joe Blocks writes about everything. replaceFirst = Joe Blocks about this, and John Doe writes about that, and John Wayne writes about everything.

输出中的换行和缩进是为了可读而增加的注意第1个字符串中所有出现 John 后跟一个单词 的地方,都被替换为 Joe Blocks 第2个字符串中,只有第一个出现的被替换appendReplacement() + appendTail()。

appendReplacement() 和 appendTail() 方法用于替换输入文本中的字符串短语,同时把替换后的字符串附加到一个 StringBuffer 中当find() 方法找到一个匹配项时,可以调用 appendReplacement() 方法,这会导致输入字符串被增加到StringBuffer 中,而且匹配文本被替换。

从上一个匹配文本结尾处开始,直到本次匹配文本会被拷贝appendReplacement() 会记录拷贝StringBuffer 中的内容,可以持续调用find(),直到没有匹配项直到最后一个匹配项目,输入文本中剩余一部分没有拷贝到 StringBuffer. 这部分文本是从最后一个匹配项结尾,到文本末尾部分。

通过调用 appendTail() 方法,可以把这部分内容拷贝到 StringBuffer 中.String text    =          "John writes about this, and John Doe writes about that," +                  " and John Wayne writes about everything."        ; String patternString1 = "((John) (.+?)) "; Pattern      pattern      = Pattern.compile(patternString1); Matcher      matcher      = pattern.matcher(text); StringBuffer stringBuffer = new StringBuffer(); while(matcher.find()){    matcher.appendReplacement(stringBuffer, "Joe Blocks ");    System.out.println(stringBuffer.toString()); } matcher.appendTail(stringBuffer); System.out.println(stringBuffer.toString());

注意我们在while循环中调用appendReplacement() 方法在循环完毕后调用appendTail() 代码输出如下:Joe Blocks Joe Blocks about this, and Joe Blocks Joe Blocks about this, and Joe Blocks writes about that, and Joe Blocks Joe Blocks about this, and Joe Blocks writes about that, and Joe Blocks writes about everything.。

Java 正则表达式语法为了更有效的使用正则表达式,需要了解正则表达式语法正则表达式语法很复杂,可以写出非常高级的表达式只有通过大量的练习才能掌握这些语法规则本篇文字,我们将通过例子了解正则表达式语法的基础部分。

介绍重点将会放在为了使用正则表达式所需要了解的核心概念,不会涉及过多的细节详细解释,参见 Java DOC 中的 Pattern 类.基本语法在介绍高级功能前,我们先快速浏览下正则表达式的基本语法字符是正则表达式中最经常使用的的一个表达式,作用是简单的匹配一个确定的字符。

例如:John这个简单的表达式将会在一个输入文本中匹配John文本可以在表达式中使用任意英文字符也可以使用字符对于的8进制,16进制或unicode编码表示例如:101 \x41 \u0041以上3个表达式 都表示大写字符A。

第一个是8进制编码(101),第2个是16进制编码(41),第3个是unicode编码(0041).字符分类字符分类是一种结构,可以针对多个字符匹配而不只是一个字符换句话说,一个字符分类匹配输入文本中的一个字符,对应字符分类中多个允许字符。

例如,你想匹配字符 a,b 或c,表达式如下:[abc]用一对方括号[] 表示字符分类方括号本身并不是要匹配的一部分可以用字符分类完成很多事例如想要匹配单词John,首字母可以为大写和小写J.[Jj]ohn。

字符分类[Jj] 匹配J或j,剩余的 ohn 会准确匹配字符ohn.预定义字符分类正则表达式中有一些预定义的字符分类可以使用例如, \d 表示任意数字, \s 表示任意空白字符,\w 表示任意单词字符预定义字符分类不需要括在方括号里,当然也可以组合使用

\d [\d\s]第1个匹配任意数字,第2个匹配任意数字或空白符完整的预定义字符分类列表,在本文最后列出边界匹配正则表达式支持匹配边界,例如单词边界,文本的开头或末尾例如,\w 匹配一个单词,^匹配行首,$ 匹配行尾。

^This is a single line$上面的表达式匹配一行文本,只有文本 This is a single line注意其中的行首和行尾标志,表示不能有任何文本在文本的前面后后面,只能是行首和行尾。

完整的匹配边界列表,在本文最后列出量词匹配量词可以匹配一个表达式多次出现例如下列表达式匹配字母A 出现0次或多次A*量词 * 表示0次或多次+ 表示1次或多次? 表示0次或1次还有些其他量词,参见本文后面的列表。

量词匹配分为 饥饿模式,贪婪模式,独占模式饥饿模式 匹配尽可能少的文本贪婪模式匹配尽可能多的文本独占模式匹配尽可能多的文本,甚至导致剩余表达式匹配失败以下演示饥饿模式,贪婪模式,独占模式区别假设以下文本:。

John went for a walk, and John fell down, and John hurt his knee.饥饿模式下 表达式:John.*?这个表达式匹配John 后跟0个或多个字符。

. 表示任意字符* 表示0或多次? 跟在 * 后面,表示 * 采用饥饿模式饥饿模式下,量词只会匹配尽可能少的字符,即0个字符上例中的表达式将会匹配单词John,在输入文本中出现3次如果改为贪婪模式,表达式如下:。

John.*贪婪模式下,量词会匹配尽可能多的字符现在表达式会匹配第一个出现的John,以及在贪婪模式下 匹配剩余的所有字符这样,只有一个匹配项最后,我们改为独占模式:John.*+hurt*后跟+ 表示独占模式量词。

这个表达式在输入文本中没有匹配项,尽管文本中包括 John 和 hurt. 为什么会这样? 因为 .*+ 是独占模式与贪婪模式下,尽可能多的匹配文本,以使整个表达式匹配不同独占模式会尽可能的多的匹配,但不考虑表达式剩余部分是否能匹配上。

.*+ 将会匹配第一个John之后的所有字符,这会导致表达式中剩余的 hurt 没有匹配项如果改为贪婪模式,会有一个匹配项表达式如下:John.*hurt逻辑操作符正则表达式支持少量的逻辑运算(与,或,非)。

与操作是默认的,表达式 John ,意味着J 与 o与h与n或操作需要显示指定,用 | 表示例如表达式 John|hurt 意味着John 或 hurt 字符.任意英文字母\\反斜杠, 单独的反斜杠做为转义字符,与其他特殊字符一起使用。

如果想匹配反斜杠本身,需要转义两个反斜杠实际匹配一个反斜杠n字符的8进制表示.n 在0至7之间取值nn字符的8进制表示.n 在0至7之间取值mnn字符的8进制表示. m 在0至3之间取值, n 在0至7之间取值

\xhh字符的16进制表示.\uhhhh字符的16进制表示 0xhhhh. 对应unicode 编码字符\t缩进符.\n换行符 (unicode: ‘\u000A’)\r回车符 (unicode: ‘\u000D’)

\f制表符 (unicode: ‘\u000C’)\a警报(铃声)字符 (unicode: ‘\u0007′)\e转义符 (unicode: ‘\u001B’)\cx控制符 x字符分类[abc]匹配 a, 或 b 或 c

[^abc]匹配不是a,b,c 的字符,是否定匹配[a-zA-Z]匹配a 到 z ,A到Z 直接的字符,是范围匹配[a-d[m-p]]匹配a到d之间字符或 m到p之间字符,是并集匹配[a-z&&[def]]

匹配 d, e, 或 f. 是交集匹配 (这里是在范围 a-z和字符def之间取交集).[a-z&&[^bc]]匹配a-z 之间所有字符,排除bc的字符是减法匹配[a-z&&[^m-p]]匹配a-z 之间所有字符,排除m-p之间的字符是减法匹配。

内置字符分类.匹配任意一个字符,根据创建Pattern是传入的标志,可能匹配行结尾符\d匹配任意数字 [0-9]\D匹配任意非数字 [^0-9]\s匹配任意空白符 (空格, 缩进, 换行,回车)\S匹配任意非空白符

\w匹配任意单词\W匹配任意非单词边界匹配^匹配行首$匹配行尾\b匹配单词边界\B匹配非单词边界\A匹配文本开头\G匹配前一匹配项结尾\ZMatches the end of the input text except the final terminator if any

\z匹配文本结尾量词贪婪模式饥饿模式独占模式X?X??X?+匹配0或1次X*X*?X*+匹配0或多次X+X+?X++匹配1或多次X{n}X{n}?X{n}+匹配n次X{n,}X{n,}?X{n,}+匹配最少n次

X{n, m}X{n, m}?X{n, m}+匹配最少n次,最多m次

Oracle学习中心微信号:oraclewdpOracle大学生实训基地官网:www.oracle-suwen.com

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

河南中青旅行社综合资讯 奇遇综合资讯 盛世蓟州综合资讯 综合资讯 游戏百科综合资讯 新闻86281