Skip to main content

Home/ InfokeyDEV/ Group items tagged regexp

Rss Feed Group items tagged

Benx Shen

Regular Expression Tool - 6 views

Benx Shen

Groovy - Regular Expressions - 0 views

  • Groovy supports regular expressions natively using the ~"pattern" expression
    • Benx Shen
       
      Groovy 對於 regexp 的支援有 3 個特殊的表示方式:
      ~"pattern" (create java.util.regex.Pattern)=~ (create java.util.regex.Matcher)==~ (do Matcher.matches() )
  • // lets create a regex Pattern def pattern = ~/foo/ assert pattern instanceof Pattern
  • Groovy also supports the =~ (create Matcher) and ==~ (matches regex) operators.
  • ...6 more annotations...
  • Since a Matcher coerces to a boolean by calling its find method, the =~ operator is consistent with the simple use of Perl's =~ operator, when it appears as a predicate (in 'if', 'while', etc.). The "stricter-looking" ==~ operator requires an exact match of the whole subject string.
  • def matcher = "\$abc." =~ /\$(.*)\./ // no need to double-escape! assert "\\\$(.*)\\." == /\$(.*)\./ matcher.matches(); // must be invoked assert matcher.group(1) == "abc" // is one, not zero
  • def m = "foobarfoo" =~ /o(b.*r)f/ assert m[0][1] == "bar"
  • // lets create a Matcher def matcher = "cheesecheese" =~ /cheese/ assert matcher instanceof Matcher answer = matcher.replaceAll("edam")
    • Benx Shen
       
      以下是一些 groovy regexp 的程式碼,請特別注意劃線的部份!
  • // fancier group demo matcher = "\$abc." =~ "\\\$(.*)\\." matcher.matches(); // must be invoked [Question: is this still true? Not in my experience with jsr-04.] assert matcher.group(1) == "abc" // is one, not zero
    • Benx Shen
       
      這裡需要特別注意的是,如果想要使用 matcher.group() 方法,那麼必須先執行 matcher.matches() 方法呼叫(我記得呼叫 find() 也行)。然而,如果是直接使用 groovy 的語法,那麼就可以直接使用 matcher[0][?] 的用法了!
1 - 6 of 6
Showing 20 items per page