Created
October 10, 2010 16:24
-
-
Save ikikko/619363 to your computer and use it in GitHub Desktop.
g100pon #59 正規表現(基本編)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g100pon #59 正規表現(基本編) | |
def target = 'The rain in Spain stays mainly in the plain!' | |
def pattern = /\b\w*ain\b/ // '*ain'で終わる単語 | |
// ========== パターン検索 ========== | |
// String.eachMatch | |
def eachMatch = '' | |
target.eachMatch(pattern) {match -> | |
eachMatch += match + ' ' | |
} | |
assert eachMatch == 'rain Spain plain ' | |
// Matcher.each | |
def each = '' | |
(target =~ pattern).each {match -> | |
each += match + ' ' | |
} | |
assert each == 'rain Spain plain ' | |
// ========== パターン置換 ========== | |
// String.replaceAll | |
def replaceAll = target.replaceAll(pattern) { | |
// 全ての単語の'ain'を'___'に置換 | |
it-'ain'+'___' | |
} | |
assert replaceAll == 'The r___ in Sp___ stays mainly in the pl___!' | |
// ========== 分類 ========== | |
// switchで正規表現を使う | |
switch('bear') { | |
case ~/..../ : break // 単語が4文字の場合 | |
default : assert false | |
} | |
// grepで正規表現を使う | |
def beasts = ['bear', 'wolf', 'hogee', 'fug'] | |
def grep = beasts.grep(~/..../) | |
assert grep == ['bear', 'wolf'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment