Groovy使用~”pattern” 来支持正则表达式,它将使用给定的模式字符串创建一个编译好的Java Pattern 对象。Groovy也支持 =~(创建一个Matcher)和 ==~ (返回boolean,是否给定的字符串匹配这个pattern)操作符。
对于groups的匹配, matcher[index] 是一个匹配到的group字符串的List或者string。
1 |
import java.util.regex.Matcher |
2 |
import java.util.regex.Pattern |
3 |
// ~ creates a Pattern from String |
5 |
assert pattern instanceof Pattern |
6 |
assert pattern.matcher("foo").matches() // returns TRUE |
7 |
assert pattern.matcher("foobar").matches() // returns FALSE, because matches() must match whole String |
9 |
// =~ creates a Matcher, and in a boolean context, it's "true" if it has at least one match, "false" otherwise. |
10 |
assert "cheesecheese" =~ "cheese" |
11 |
assert "cheesecheese" =~ /cheese/ |
12 |
assert "cheese" == /cheese/ /*they are both string syntaxes*/ |
13 |
assert ! ("cheese" =~ /ham/) |
15 |
// ==~ tests, if String matches the pattern |
16 |
assert "2009" ==~ /\d+/ // returns TRUE |
17 |
assert "holla" ==~ /\d+/ // returns FALSE |
19 |
// lets create a Matcher |
20 |
def matcher = "cheesecheese" =~ /cheese/ |
21 |
assert matcher instanceof Matcher |
23 |
// lets do some replacement |
24 |
def cheese = ("cheesecheese" =~ /cheese/).replaceFirst("nice") |
25 |
assert cheese == "nicecheese" |
26 |
assert "color" == "colour".replaceFirst(/ou/, "o") |
28 |
cheese = ("cheesecheese" =~ /cheese/).replaceAll("nice") |
29 |
assert cheese == "nicenice" |
32 |
// You can also match a pattern that includes groups. First create a matcher object, |
33 |
// either using the Java API, or more simply with the =~ operator. Then, you can index |
34 |
// the matcher object to find the matches. matcher[0] returns a List representing the |
35 |
// first match of the regular expression in the string. The first element is the string |
36 |
// that matches the entire regular expression, and the remaining elements are the strings |
37 |
// that match each group. |
38 |
// Here's how it works: |
39 |
def m = "foobarfoo" =~ /o(b.*r)f/ |
40 |
assert m[0] == ["obarf", "bar"] |
41 |
assert m[0][1] == "bar" |
43 |
// Although a Matcher isn't a list, it can be indexed like a list. In Groovy 1.6 |
44 |
// this includes using a collection as an index: |
46 |
matcher = "eat green cheese" =~ "e+" |
48 |
assert "ee" == matcher[2] |
49 |
assert ["ee", "e"] == matcher[2..3] |
50 |
assert ["e", "ee"] == matcher[0, 2] |
51 |
assert ["e", "ee", "ee"] == matcher[0, 1..2] |
53 |
matcher = "cheese please" =~ /([^e]+)e+/ |
54 |
assert ["se", "s"] == matcher[1] |
55 |
assert [["se", "s"], [" ple", " pl"]] == matcher[1, 2] |
56 |
assert [["se", "s"], [" ple", " pl"]] == matcher[1 .. 2] |
57 |
assert [["chee", "ch"], [" ple", " pl"], ["ase", "as"]] == matcher[0,2..3] |
58 |
// Matcher defines an iterator() method, so it can be used, for example, |
59 |
// with collect() and each(): |
60 |
matcher = "cheese please" =~ /([^e]+)e+/ |
61 |
matcher.each { println it } |
63 |
assert matcher.collect { it }?? == |
64 |
[["chee", "ch"], ["se", "s"], [" ple", " pl"], ["ase", "as"]] |
65 |
// The semantics of the iterator were changed by Groovy 1.6. |
66 |
// In 1.5, each iteration would always return a string of the entire match, ignoring groups. |
67 |
// In 1.6, if the regex has any groups, it returns a list of Strings as shown above. |
69 |
// there is also regular expression aware iterator grep() |
70 |
assert ["foo", "moo"] == ["foo", "bar", "moo"].grep(~/.*oo$/) |
71 |
// which can be written also with findAll() method |
72 |
assert ["foo", "moo"] == ["foo", "bar", "moo"].findAll { it ==~ /.*oo/ } |
More Examples
匹配每行开头的大写单词:
15 |
assert expected == before.replaceAll(/(?m)^\w+/, |
16 |
{ it[0].toUpperCase() + ((it.size() > 1) ? it[1..-1] : '') }) |
匹配字符串中的每一个大写单词
1 |
assert "It Is A Beautiful Day!" == |
2 |
("it is a beautiful day!".replaceAll(/\w+/, |
3 |
{ it[0].toUpperCase() + ((it.size() > 1) ? it[1..-1] : '') })) |
使用 .toLowerCase() 让其他单词小写:
1 |
assert "It Is A Very Beautiful Day!" == |
2 |
("it is a VERY beautiful day!".replaceAll(/\w+/, |
3 |
{ it[0].toUpperCase() + ((it.size() > 1) ? it[1..-1].toLowerCase() :'') })) |
Gotchas
怎么使用String.replaceAll()的反向引用
GStrings 可能和你期望的不一样
1 |
def replaced = "abc".replaceAll(/(a)(b)(c)/, "$1$3") |
产生一个类似于下面的错误:
[] illegal string body character after dollar sign:
解决办法:: either escape a literal dollar sign “\$5″ or bracket the value expression “${5}” @ line []
Solution:
Use ‘ or / to delimit the replacement string:
1 |
def replaced = "abc".replaceAll(/(a)(b)(c)/, '$1$3') |
- groovy regex groups(groovy正则表达式组)
先看一个java正则表达式的例子. import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestM ...
- Groovy正则表达式复杂逻辑判断实例
下面的两个pattern(p1和p2)分别代表了(A or B) and (C or D)和(A and B) or (C and D)的跨行匹配结果,当然还可以用正则表达式构建更复杂的pattern ...
- groovy中的正则表达式操作符【groovy】
groovy中对于正则表达式的书写进行了简化,同时引入了新的操作符,使得正则表达式使用起来比较方便简单. 对于书写的改进: 比如 assert "\\d" == /\d/ 也就是在 ...
- Groovy入门经典 随书重点
1 数值和表达式 1.1数值 整数是Integer类的实例 有小数部分的数值是BigDecimal类的实例 不同于java,没有基础数据类型 一切皆对象的概念重于java 1.2表达式 两个整数的除法 ...
- 30分钟groovy快速入门并掌握(ubuntu 14.04+IntelliJ 13)
本文适合于不熟悉 Groovy,但想快速轻松地了解其基础知识的 Java开发人员.了解 Groovy 对 Java 语法的简化变形,学习 Groovy 的核心功能,例如本地集合.内置正则表达式和闭包. ...
- Java Gradle入门指南之内建与定制任务类(buildSrc、Groovy等)
上一篇随笔介绍了Gradle的安装与任务管理,这篇着重介绍Gradle的内建任务(in-built tasks)与自定义任务(custom tasks),借助Gradle提供的众多内建任务类型 ...
- atitit groovy 总结java 提升效率
atitit groovy 总结java 提升效率 #---环境配置 1 #------安装麻烦的 2 三.创建groovy项目 2 3. 添加 Groovy 类 2 4. 编译运行groovy类 ...
- Groovy split竖杆注意
前几天将09年写的一个Asp程序使用Grails改造重写,在处理手机号码Split的时候,Asp代码: dim phoneArr phoneArr = split(phones,"|&quo ...
- 新学习的语言Groovy
什么是 Groovy? Groovy 是 JVM 的一个替代语言 —替代 是指可以用 Groovy 在 Java 平台上进行 Java 编程,使用方式基本与使用 Java 代码的方式相同.在编写新应用 ...
- Groovy轻松入门——通过与Java的比较,迅速掌握Groovy (更新于2008.10.18)
摘自: http://www.blogjava.net/BlueSUN/archive/2007/03/10/103014.html Groovy轻松入门--通过与Java的比较,迅速掌握Groovy ...
随机推荐
- mysqli常用错误处理函数
mysqli扩展库包含三个类库,分别是mysqli连接库,mysqli_result处理结果集库和预处理库: 当使用select语句返回的结果集就是mysqli_result类库的对象,所以就可以用这 ...
- PYTHON FABRIC实现远程操作和部署
转载至:http://wklken.me/posts/2013/03/25/python-tool-fabric.html fabric title是开发,但是同时要干开发测试还有运维的活 (o(╯□ ...
- RDLC系列之四 常见错误
解决 RDLC 报表自动分页表头显示问题 原文:http://www.th7.cn/Program/net/201207/85445.shtml RDLC是用XML来描述一个报表相关的一切,只需要在& ...
- OV7725学习(二)
首先要配置OV7725摄像头的寄存器,遵循的是SCCB协议,配置之前需要1ms的时间等待,保证系统稳定,而且刚开始要丢弃前10帧的数据,因为认为前10帧的数据是不稳定的,图1就是数据手册上关于这一点的 ...
- MySQL基础 - 外键和约束
在工作中经常会遇到不少不同的观点,比如对于数据库来说那就是是否要设置外键,设置外键的理由自然不必多说,而不设置外键的理由多半为设置外键影响性能,但就目前工作来讲,还没有涉及到因为外键而引发的数据库瓶颈 ...
- 2016北京PHP39期 ThinkPHP Discuz Dedecms 微信开发视频教程
2016北京PHP39期 ThinkPHP Discuz Dedecms 微信开发视频教程 所有项目均带有软件,笔记,视频,源码 日期 课程(空内容代表放假) 2015/7/10 星期五 开学典礼 ...
- IOS开发之——Masonry 只支持OC,暂不支持swift
前言 1 MagicNumber -> autoresizingMask -> autolayout 以上是纯手写代码所经历的关于页面布局的三个时期 在iphone1-iphone3gs时 ...
- iOS端给unity发送消息,实现两者交互。
上一篇我们简单说了一下unity发消息给iOS端.现在我们就来说一下iOS端给unity发送消息的简单使用. 首先iOS端做得事情其实很简单就一句话,直接上代码 /** * 第一个参数:是unity那 ...
- 【总结】学习Socket编写的聊天室小程序
1.前言 在学习Socket之前,先来学习点网络相关的知识吧,自己学习过程中的一些总结,Socket是一门很高深的学问,本文只是Socket一些最基础的东西,大神请自觉绕路. 传输协议 TCP:Tra ...
- 『设计』Laura.Compute 设计思路
前言: 前一篇文章 <『开源』也顺手写一个 科学计算器:重磅开源> ,继 Laura.Compute 算法开源之后,有 博客园 园友 希望公开一下 Laura.Compute算法 的 设计 ...