Groovy正则表达式

    技术2026-08-19  18

    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)