9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nim文字列操作(正規表現)

Last updated at Posted at 2016-06-01

概要

nimの正規表現ライブラリの操作コツコツと。
reモジュールではなく、nreモジュールを利用しています。
nreモジュールは、optionsライブラリを利用しているっぽく、ちょっとモダンな雰囲気がする正規表現ライブラリとなっています。

以下メモ

マッチ

import nre,options,strutils
block:
  echo "1.match=>","abc".match(re"abc")
  echo "2.match=>","abcdef".match(re"^abc")
  echo "3.unmatch=>","abcdef".match(re"def$")
  echo "4.match=>","abcdef".match(re".+def$")
(stdout)
1.match=>Some(abc)
2.match=>Some(abc)
3.unmatch=>None[RegexMatch]
4.match=>Some(abcdef)

検索

import nre,options,strutils
block:
  echo "1.find=>","abc".find(re"abc")
  echo "2.find=>","abcdef".find(re"^abc")
  echo "3.find=>","abcdef".find(re"def$")
  echo "4.find=>","abcdef".find(re".+def$")
(stdout)
1.find=>Some(abc)
2.find=>Some(abc)
3.find=>Some(def)
4.find=>Some(abcdef)

分割(split)

import nre,options,strutils
block:
  let s1 = "Test,test; test. Test."
  echo s1.split(re"[,;.] ?")   == @["Test", "test", "test", "Test", ""]
  echo s1.split(re"([,;.]) ?") == @["Test", ",", "test", ";", "test", ".", "Test", ".", ""]
(stdout)
true
true

置換(置換指定のパターンがいくつかありますよ)

import nre,options,strutils
block:
  # procで置換
  echo "1.replace=>","abc".replace( re"(\w)", proc (m: RegexMatch) : string =
    #var s:string = m.match
    #m.str.toUpper
    m.match.toUpper
  )
  # procで置換
  echo "2.replace=>","abc".replace( re"(abc)", proc (m: string) : string =
    m & "HELLO"
  )
  # 文字列で置換
  echo "3.replace=>","abcdef".replace( re"(?<word1>abc)(?<word2>def)", "[[$word1][$word2]]")
  # doで置換
  echo "4.replace=>", "abc".replace(re"(abc)")
    do (m: string) -> string :
      m & "HELLO"
(stdout)
1.replace=>ABC
2.replace=>abcHELLO
3.replace=>[[abc][def]]
4.replace=>abcHELLO

オプションテスト(マッチ後のオブジェクト)

import nre,options,strutils
block:
  var m = "abc123DEF".match(re"([a-z]+)\d+([A-Z]+)").get
  echo "str=>",m.str
  echo "match=>",m.match
  echo "matchBounds=>",m.matchBounds
  echo "captures[0]=>",m.captures[0]
  echo "captures[1]=>",m.captures[1]
(stdout)
str=>abc123DEF
match=>abc123DEF
matchBounds=>(a: 0, b: 8)
captures[0]=>abc
captures[1]=>DEF

iteratorサンプル

import nre,options,strutils
block:
  let line = "123 456 789"
  for m in line.findIter(re"\d+") :
    echo m.match
(stdout)
123
456
789
9
4
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
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?