...
Why does this code fail?
| Code Block |
|---|
def matcher = "/home/me/script/test.groovy" =~ /\.groovy/
assert matcher.matches()
|
...
So "/\.groovy/" is just a subsequence.
You must use
| Code Block |
|---|
def matcher = "/home/me/script/test.groovy" =~ /.*\.groovy/
|
...
A pattern is not very useful alone. He's just waiting input to process through a matcher.
| Code Block |
|---|
def pattern = ~/groovy/
def matcher = pattern.matcher('my groovy buddy')
|
...
A matcher with /groovy/ pattern finds a matching subsequence in the 'my groovy buddy' sequence.
On the contrary the whole sequence doesn't match the pattern.
| Code Block |
|---|
def m = c.matcher('my groovy buddy')
assert m.find()
assert m.matches() == false
|
Application: to filter a list of names.
| Code Block | ||
|---|---|---|
| ||
def list = ['groovy', '/a/b/c.groovy', 'myscript.groovy', 'groovy.rc', 'potatoes', 'groovy.'] // find all items whom a subsequence matches /groovy/ println list.findAll{ it =~ /groovy/ } // => [ "groovy", "/a/b/c.groovy", "myscript.groovy", "groovy.rc", "groovy." ] // find all items who match exactly /groovy/ println list.findAll{ it ==~ /groovy/ } // => [ "groovy" ] // find all items who match fully /groovy\..*/ ('groovy' with a dot and zero or more char trailing) println list.findAll{ it ==~ /groovy\..*/ } // => ["groovy.rc", "groovy."] |
...