程式扎記: [ GroovyGN ] Matchers for Regular Expressions

標籤

2016年5月24日 星期二

[ GroovyGN ] Matchers for Regular Expressions

Source From Here 
Preface 
In a previous post we learned how to create a java.util.regex.Pattern object. Now we learn how to create a java.util.regex.Matcher object and use it for finding and matching values. 

In Groovy we use the =~ operator (find operator) to create a new matcher object. If the matcher has any match results we can access the results by invoking methods on the matcher object. But Groovy wouldn't by groovy if we could access the results easier. Groovy enhances the Matcher class so the data is available with an array-like syntax. If we use groups in the matcher the result can be accessed with a multidimensional array. Although the result of the =~operator is a matcher object in a conditional statement the result will be converted to a Boolean values. 

We can use a second operator, ==~ (match operator), to do exact matches. With this operator the matches() method is invoked on the matcher object. The result is a Boolean value. 

Sample Code 
  1. def finder = ('groovy' =~ /gr.*/)  
  2. assert finder instanceof java.util.regex.Matcher  
  3.   
  4. def matcher = ('groovy' ==~ /gr.*/)  
  5. assert matcher instanceof Boolean  
  6.   
  7. assert 'Groovy rocks!' =~ /Groovy/  // =~ in conditional context returns boolean.  
  8. assert !('Groovy rocks!' ==~ /Groovy/)  // ==~ looks for an exact match.  
  9. assert 'Groovy rocks!' ==~ /Groovy.*/  
  10.   
  11. def cool = /gr\w{4}/  // Start with gr followed by 4 characters.  
  12. def findCool = ('groovy, java and grails rock!' =~ /$cool/)  
  13. assert 2 == findCool.count  
  14. assert 2 == findCool.size()  // Groovy adds size() method.  
  15. assert 'groovy' == findCool[0]  // Array-like access to match results.  
  16. assert 'grails' == findCool.getAt(1)  
  17.   
  18. // With grouping we get a multidimensional array.  
  19. def group = ('groovy and grails, ruby and rails' =~ /(\w+) and (\w+)/)  
  20. assert group.hasGroup()  
  21. assert 2 == group.size()  
  22. assert ['groovy and grails''groovy''grails'] == group[0]  
  23. assert 'rails' == group[1][2]  
  24.   
  25. // Use matcher methods.  
  26. assert 'Hi world' == ('Hello world' =~ /Hello/).replaceFirst('Hi')  
  27.   
  28. // Groovy matcher syntax can be used in other methods.  
  29. assert ['abc'] == ['def''abc''123'].findAll { it =~ /abc/ }  
  30. assert [falsefalsetrue] == ['def''abc''123'].collect { it ==~ /\d{3}/ }  
Supplement 
[ In Action ] The Simple Groovy datatypes - Working with regular expressions 
Groovy Goodness: Using Regular Expression Pattern Class 
Groovy Goodness: Remove Part of String With Regular Expression Pattern 
Groovy Goodness: Partial Matches 
Grails Goodness: Checking Results from Forward Action in Controller Unit Tests 
Groovy Goodness: the Switch Statement

沒有留言:

張貼留言

網誌存檔