Groovy正则表达式

regex查找操作符  =~

返回matcher对象

 

regex匹配操作符  ==~

返回boolean型,匹配的是整个 字符串

 

利用GString我们可以做一些有趣的事情。

word=//w+/

assert 'asdasdadasd'==~/($word $word)*/

word是不是比 //w+/更加容易理解?

 

通用形式

String =~pattern

 

groovy中

1,String有一个方法 eachMatch它以一个规则pattern和一个闭包作为参数

 

myStr = 'this rain in spain stays mainly in the plain!'

bounds=//b/

pattern=/$bounds/w*ain$bounds/

found=' '

myStr.eachMatch(pattern){arg -> found+=arg[0]+' '}

assert found==' rain spain plain '

 

2,matcher也有一个叫each的方法,它以闭包为参数

(myStr=~pattern).each{arg->ound+=arg[0]+' '}

结果是一样的

 

-------------------------------------------------

print myStr.replaceAll(pattern){it-'ain'+'_'}

结果是 this r_ in sp_ stays m_ly in the pl_!

其中it指向匹配子串这和{it->it-'ain'+'_'}一样的效果

 

在此发现了string的 - + 加减符号的用法

myStr = 'this rain in spain stays mainly in the plain!'

print myStr-'a'-'a'-'a'

结果会减掉第一次第二次第三次出现的a

而+是在字符串尾部加上的。

---------------------------------------------

关于matcher

返回的matcher是数组

如果pattern即模式里面没有用到组

可以通过matcher.hasGroup()检查

这macther[x]不是一个数组

否则

matcher[x]同样也是一个数组,比如macher[x]=['all','g1','g2'],其中第一个为全部匹配子串,g1,g2这些后面的为组匹配子串

-----------------------

----------------------------

 

regex模式操作符  ~String

~//w*/  返回的是pattern对象

assert (~/../).isCase('ab')

 

pattern对象的使用 除了上面的isCase(str)方法外,还有在switch语句和grep方法中的应用。

它还可以用呀switch语句和数组中

switch('ab'){

case  ~/../:assert true;break

default :assert false; 

}

 

beasts=['a','b','cc']

assert beasts.grep(~/./)==['a','b']

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值