`
Javabengou
  • 浏览: 170607 次
  • 性别: Icon_minigender_1
  • 来自: 郴州
社区版块
存档分类
最新评论

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'

更多的正則表達式操作符可以去參考官方文檔。

 

 

 

 

分享到:
评论
1 楼 magibt 2008-05-04  
留言,走人

相关推荐

Global site tag (gtag.js) - Google Analytics