Skip to content

Instantly share code, notes, and snippets.

@ikikko
Created October 10, 2010 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikikko/619363 to your computer and use it in GitHub Desktop.
Save ikikko/619363 to your computer and use it in GitHub Desktop.
g100pon #59 正規表現(基本編)
// 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