LoginSignup
1
2

More than 5 years have passed since last update.

GroovyでPattern.compileする

Posted at

はじめ

記事名でえ?となった方も居るでしょう。

いや

import java.util.regex.Pattern

def regex=Pattern.compile('牛(?:丼|めし)')

とすれば良いんじゃないか、と

では例のアレで分かりやすく(?)説明します

じゃあどうするの?

I have ...

def regex='牛(?:丼|めし)'

I have ...

~

or

bitwiseNegate()

Oh!

def regex= ~'牛(?:丼|めし)'

これだけ?

だけ。
正規表現が何のネタかはお察し下さい

説明

以下のコードはGroovyでは(ほぼ)等価です。

普通にPatternを使う(1)
import java.util.regex.Pattern

def regex=Pattern.compile('牛(?:丼|めし)')
~を使う(2)
def regex= ~'牛(?:丼|めし)'
bitwiseNegate()を使う(3)
def regex='牛(?:丼|めし)'.bitwiseNegate()

厳密には
1≒2,32==3ですね(2と3はMetaClassで上書きできてしまうため)
2と3では、1とは異なりフラグは指定できません。(2と3を使ってPatten.compileした場合、フラグは0になります。)

利点としては、importが省略できる事ですね(defで宣言すればPatternクラスを出現させなくて済む)

注意

このコードはエラーになります。

def regex=~'牛(?:丼|めし)'

=~'=~"と書くのは駄目みたいですね。
最初そう書いてIntelliJ IDEAに怒られてから3に直してIntelliJ IDEAにまた怒られたのは内緒

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2