Advertisement
fatimacasau

regular expressions

Feb 5th, 2012
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 1.08 KB | None | 0 0
  1. import java.util.regex.Matcher
  2. import java.util.regex.Pattern
  3.  
  4.  
  5. // ~ creates a Pattern from String
  6. def pattern = ~/foo/
  7. assert pattern instanceof Pattern
  8. assert pattern.matcher("foo").matches()    // returns TRUE
  9. assert !pattern.matcher("foobar").matches() // returns FALSE, because matches() must match whole String
  10.  
  11. // =~ creates a Matcher, and in a boolean context, it's "true" if it has at least one match, "false" otherwise.
  12. assert "cheesecheese" =~ "cheese"
  13. assert "cheesecheese" =~ /cheese/
  14. assert "cheese" == /cheese/   /*they are both string syntaxes*/
  15. assert ! ("cheese" =~ /ham/)
  16.  
  17. // ==~ tests, if String matches the pattern
  18. assert "2009" ==~ /\d+/  // returns TRUE
  19. assert !("holla" ==~ /\d+/) // returns FALSE
  20.  
  21. // lets create a Matcher
  22. def matcher = "cheesecheese" =~ /cheese/
  23. assert matcher instanceof Matcher
  24.  
  25. // lets do some replacement
  26. def cheese = ("cheesecheese" =~ /cheese/).replaceFirst("nice")
  27. assert cheese == "nicecheese"
  28. assert "color" == "colour".replaceFirst(/ou/, "o")
  29.  
  30. cheese = ("cheesecheese" =~ /cheese/).replaceAll("nice")
  31. assert cheese == "nicenice"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement