正则表达式

Groovy语言本身就支持正则表达式,语法是~“pattern”,它将根据给定的模式字符串,将其编译成Java的Pattern对象。此外Groovy还支持=~ (创建一个 Matcher)和==~ (匹配正则表达式) 操作符。

从jsr-03发布以来,对于匹配(matchers)中含有分组的情况, matcher[index]可能是一个匹配的字符串,也可能是匹配到的分组的字符串列表。

看看如下示例:

import java.util.regex.Matcher
import java.util.regex.Pattern
 
assert "cheesecheese" =~ "cheese"
assert "cheesecheese" =~ /cheese/
assert "cheese" == /cheese/   /*they are both string syntaxes*/
 
// lets create a regex Pattern
//创建一个正则表达式模式
def pattern = ~/foo/
assert pattern instanceof Pattern
assert pattern.matcher("foo").matches()
 
// lets create a Matcher
//创建一个模式匹配
def matcher = "cheesecheese" =~ /cheese/
assert matcher instanceof Matcher
answer = matcher.replaceAll("edam")
 
// lets do some replacement
//做一些替换操作
def cheese = ("cheesecheese" =~ /cheese/).replaceFirst("nice")
assert cheese == "nicecheese"
 
// simple group demo
// You can also match a pattern that includes groups.  First create a matcher object, either
// using the Java API, or more simply with the =~ operator.  Then, you can index the matcher
// object to find the matches.  matcher[0][1] means the 0th match of the whole pattern (with the
// =~ operator the pattern may match the string in more than one place), and the 1st group within
// that match.  Here's how it works:
//简单的分组演示
//你也可以匹配一个包含分组的模式。首先使用JavaAPI或者=~操作符创建一个匹配对象,
//然后可以通过matcher对象来引用找到的索引匹配。
//matcher[0][1]意味着全部模式的第0个匹配(使用=~操作符,模式可以匹配到多个)和此匹配中的第一个分组。
//以下将演示如何工作的:
def m = "foobarfoo" =~ /o(b.*r)f/
assert m[0][1] == "bar"
 
// fancier group demo
matcher = "\$abc." =~ "\\\$(.*)\\."
matcher.matches(); // 必须被调用   [问题: 是true么?  在我的jsr-04实践中不是]
assert matcher.group(1) == "abc"  // 是1 而不是0
// assert matcher[1] == "abc"            // 这在jsr-03发布前可以工作
assert matcher[0] == ["\$abc.", "abc"]   // 要在jsr-03以后才可以工作
assert matcher[0][1] == "abc"            // 同上

模式还可以通过”/“定义符表达地更简洁,这样我们就不需要双份的反斜杠(\)了。看如下示例:

def matcher = "\$abc." =~ /\$(.*)\./ // no need to double-escape!
assert "\\\$(.*)\\." == /\$(.*)\./
matcher.matches(); // must be invoked
assert matcher.group(1) == "abc"  // is one, not zero
// assert matcher[1] == "abc"            // This has worked before jsr-03-release
assert matcher[0] == ["\$abc.", "abc"]   // But this should work since jsr-03-release
assert matcher[0][1] == "abc"            // This should work since jsr-03-release

因为Matcher可以通过调用它的find方法强制返回一个boolean类型,那么当它出现在一个谓词(predicate,'if', 'while'等)的时候,此时=~ 操作符同Perl的=~ 是一致的。 而”stricter-looking” ==~ 操作符要求整个字符串完全匹配。

正则表达式是从Java中引入的, Java的正则表达式和API请看这里

更多示例

def before='''
apple
orange
banana
'''
 
def expected='''
Apple
Orange
Banana
'''
 
assert expected == before.replaceAll(/(?m)^\w+/,{it[0].toUpperCase() + it[1..-1]})
 
wiki/user_guide/regular_expressions.txt · 最后更改: 2008-04-22 21:23 由 agile.guo
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki