How do I get a Boolean value for a partial match using Groovy's regex?

后端 未结 1 1558
深忆病人
深忆病人 2021-01-13 23:10

Groovy has a regular expression \"match operator\" (==~). The documentation says it returns a Boolean, but requires a \"strict match\". It does not define \"str

相关标签:
1条回答
  • 2021-01-13 23:35

    The 'foo-bar-baz' ==~ /bar/ is equal to "foo-bar-baz".matches("bar"), that is, it requires a full string match.

    The =~ operator allows partial match, that is, it may find a match/matches inside a string.

    Hence:

    println('foo-bar-baz' ==~ /bar/) // => false
    println('bar' ==~ /bar/)         // => true
    println('foo-bar-baz' =~ /bar/)  // => java.util.regex.Matcher[pattern=bar region=0,11 lastmatch=]
    

    See this Groovy demo

    If you need to check for a partial match, you cannot avoid building a Matcher object:

    use the find operator =~ to build a java.util.regex.Matcher instance

       def text = "some text to match"
       def m = text =~ /match/                                           
       assert m instanceof Matcher                                       
       if (!m) {                                                         
           throw new RuntimeException("Oops, text not found!")
       }
    

    if (!m) is equivalent to calling if (!m.find())

    Alternatively, you may use the ! twice to cast the result to correct Boolean value:

    println(!!('foo-bar-baz' =~ /bar/))
    

    Returns true.

    0 讨论(0)
提交回复
热议问题