2008-05-04
Java笨狗groovy学习笔记—Regular Expressions
正則表達式就像一把瑞士軍刀。
"potatoe" ==~ /potatoe/
假如你在groovyConsole運行它,將返回true.這裡有兩件需要注意的事情:
1.==~操作符。它類似于==操作符,但是用於匹配模式而不是計算相等性。
2.正則表達式包含在 '/'中.它會告訴Groovy這是個正則表達式而不是String.
"potatoe" ==~ /potatoe?/ "potato" ==~ /potatoe?/
這裡?表達的意思是'e'是可選的。
"motato" ==~ /potatoe?/
沒有可匹配的。
現在讓我來看些複雜的,我們定義一個方法用來測試正則表達式:
def checkSpelling(spellingAttempt, spellingRegularExpression)
{
if (spellingAttempt ==~ spellingRegularExpression)
{
println("Congratulations, you spelled it correctly.")
} else {
println("Sorry, try again.")
}
}
theRegularExpression = /Wisniewski/
checkSpelling("Wisniewski", theRegularExpression)
checkSpelling("Wisnewski", theRegularExpression)
這裡有兩件事情需要注意:
1.我們定義了函數
def checkSpelling(spellingAttempt, spellingRegularExpression)
函數是一個類似于閉包的代碼集合。函數通常擁有名字,然而閉包可以是匿名的,一旦我們定義了函數,我們就可以在以後重複使用。
在函數中的if語句中,我們判斷 spellingAttempt 參數時候匹配正則表達式通過使用==~操作符
theRegularExpression = /Wis[abcd]niewski/ // requires one of 'a', 'b', 'c' or 'd' theRegularExpression = /Wis[abcd]?niewski/ // will allow one of 'a', 'b', 'c' or 'd', but not required (like above) theRegularExpression = /Wis[a-zA-Z]niewski/ // requires one of any upper\- or lower-case letter theRegularExpression = /Wis[^abcd]niewski/ // requires one of any character that is '''not''' 'a', 'b', 'c' or 'd'
這裡使用了 *[ ]*.用來分組字符
theRegularExpression = /Wis[abcd]niewski/ // requires one of 'a', 'b', 'c' or 'd'
需要'a', 'b', 'c' , 'd'其中的一個。
theRegularExpression = /Wis[abcd]?niewski/ // will allow one of 'a', 'b', 'c' or 'd', but not required (like above)
需要'a', 'b', 'c' , 'd'其中的一個,但不是必須的,因為在[ ]後面跟隨了一個?
theRegularExpression = /Wis[a-zA-Z]niewski/ // requires one of any upper\- or lower-case letter
需要一個任意的大寫或小寫字符。
theRegularExpression = /Wis[^abcd]niewski/ // requires one of any character that is '''not''' 'a', 'b', 'c' or 'd'
任何一個不是''a', 'b', 'c' , 'd'
更多的正則表達式操作符可以去參考官方文檔。
- 16:45
- 浏览 (217)
- 评论 (1)
- 分类: Java笨狗groovy学习笔记
- 发布在 Groovy on Grails 圈子
- 相关推荐
发表评论
- 浏览: 44014 次
- 性别:

- 来自: 郴州

- 详细资料
搜索本博客
我的相册
QQ截图未命名3
共 37 张
共 37 张
最近加入圈子
最新评论
-
JSF请求处理生命周期(一 ...
我觉得1、需要解释概念2、需要用实例说话3、概念说得不错
-- by lysmart_8 -
grails and tinymce
笨狗啊,你是一心放在在groovy&grails上了啊,不错,不错。学习了。
-- by rockjava -
Grails中文文档beta发布
感谢辛苦的劳动!
-- by vdgame -
那天好友对我说他哭了
好....
-- by qieren -
Grails中文文档beta发布
-- by zengsun






评论排行榜