1 正则表达式
1.1 正则表达式
Groovy的正则表达式支持java的正则表达式,并且现在了额外易用的正则语法。
Groovy新增:将/作为String的声明,例如:/strings/,使用2个/,并无需去掉后边的/。
Table 3.
|
|
str =~ pattern |
创建一个字符串的匹配器。等同于Pattern.compile(pattern).matcher(str)。如果你想搜索,如果指定的字符(pattern)包含在该string变量中时,将会返回true。 |
==~ |
如果pattern匹配string,返回一个boolean。等同于Pattern.matches(pattern, str). |
~String |
创建一个string的pattern对象。等同于java中的Pattern.compile(str)。 |
如果你使用~操作符,像string将会转变为正则表达式。
Groovy也提供了replaceAll
方法,允许你定义一个闭包(closure)。
package first
public class RegularExpressionTest{ public static void main(String[] args) { // Defines a string with special signs def text = "John Jimbo jingeled happily ever after"
// Every word must be followed by a nonword character // Match if (text==~/(w*W+)*/){ println "Match was successful" } else { println "Match was not successful" } // Every word must be followed by a nonword character // Find if (text=~/(w*W+)*/){ println "Find was successful" } else { println "Find was not successful" }
if (text==~/^J.*/){ println "There was a match" } else { println "No match found" } def newText = text.replaceAll(/w+/, "hubba") println newText }
} |