re.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Regular expression support for Nim.
  10. ##
  11. ## This module is implemented by providing a wrapper around the
  12. ## `PCRE (Perl-Compatible Regular Expressions) <http://www.pcre.org>`_
  13. ## C library. This means that your application will depend on the PCRE
  14. ## library's licence when using this module, which should not be a problem
  15. ## though.
  16. ## PCRE's licence follows:
  17. ##
  18. ## .. include:: ../../doc/regexprs.txt
  19. ##
  20. import
  21. pcre, strutils, rtarrays
  22. const
  23. MaxSubpatterns* = 20
  24. ## defines the maximum number of subpatterns that can be captured.
  25. ## This limit still exists for ``replacef`` and ``parallelReplace``.
  26. type
  27. RegexFlag* = enum ## options for regular expressions
  28. reIgnoreCase = 0, ## do caseless matching
  29. reMultiLine = 1, ## ``^`` and ``$`` match newlines within data
  30. reDotAll = 2, ## ``.`` matches anything including NL
  31. reExtended = 3, ## ignore whitespace and ``#`` comments
  32. reStudy = 4 ## study the expression (may be omitted if the
  33. ## expression will be used only once)
  34. RegexDesc = object
  35. h: ptr Pcre
  36. e: ptr ExtraData
  37. Regex* = ref RegexDesc ## a compiled regular expression
  38. RegexError* = object of ValueError
  39. ## is raised if the pattern is no valid regular expression.
  40. when defined(gcDestructors):
  41. proc `=destroy`(x: var RegexDesc) =
  42. pcre.free_substring(cast[cstring](x.h))
  43. if not isNil(x.e):
  44. pcre.free_study(x.e)
  45. proc raiseInvalidRegex(msg: string) {.noinline, noreturn.} =
  46. var e: ref RegexError
  47. new(e)
  48. e.msg = msg
  49. raise e
  50. proc rawCompile(pattern: string, flags: cint): ptr Pcre =
  51. var
  52. msg: cstring = ""
  53. offset: cint = 0
  54. result = pcre.compile(pattern, flags, addr(msg), addr(offset), nil)
  55. if result == nil:
  56. raiseInvalidRegex($msg & "\n" & pattern & "\n" & spaces(offset) & "^\n")
  57. proc finalizeRegEx(x: Regex) =
  58. # XXX This is a hack, but PCRE does not export its "free" function properly.
  59. # Sigh. The hack relies on PCRE's implementation (see ``pcre_get.c``).
  60. # Fortunately the implementation is unlikely to change.
  61. pcre.free_substring(cast[cstring](x.h))
  62. if not isNil(x.e):
  63. pcre.free_study(x.e)
  64. proc re*(s: string, flags = {reStudy}): Regex =
  65. ## Constructor of regular expressions.
  66. ##
  67. ## Note that Nim's
  68. ## extended raw string literals support the syntax ``re"[abc]"`` as
  69. ## a short form for ``re(r"[abc]")``.
  70. when defined(gcDestructors):
  71. result = Regex()
  72. else:
  73. new(result, finalizeRegEx)
  74. result.h = rawCompile(s, cast[cint](flags - {reStudy}))
  75. if reStudy in flags:
  76. var msg: cstring = ""
  77. var options: cint = 0
  78. var hasJit: cint = 0
  79. if pcre.config(pcre.CONFIG_JIT, addr hasJit) == 0:
  80. if hasJit == 1'i32:
  81. options = pcre.STUDY_JIT_COMPILE
  82. result.e = pcre.study(result.h, options, addr msg)
  83. if not isNil(msg): raiseInvalidRegex($msg)
  84. proc rex*(s: string, flags = {reStudy, reExtended}): Regex =
  85. ## Constructor for extended regular expressions.
  86. ##
  87. ## The extended means that comments starting with `#` and
  88. ## whitespace are ignored.
  89. result = re(s, flags)
  90. proc bufSubstr(b: cstring, sPos, ePos: int): string {.inline.} =
  91. ## Return a Nim string built from a slice of a cstring buffer.
  92. ## Don't assume cstring is '\0' terminated
  93. let sz = ePos - sPos
  94. result = newString(sz+1)
  95. copyMem(addr(result[0]), unsafeAddr(b[sPos]), sz)
  96. result.setLen(sz)
  97. proc matchOrFind(buf: cstring, pattern: Regex, matches: var openArray[string],
  98. start, bufSize, flags: cint): cint =
  99. var
  100. rtarray = initRtArray[cint]((matches.len+1)*3)
  101. rawMatches = rtarray.getRawData
  102. res = pcre.exec(pattern.h, pattern.e, buf, bufSize, start, flags,
  103. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  104. if res < 0'i32: return res
  105. for i in 1..int(res)-1:
  106. var a = rawMatches[i * 2]
  107. var b = rawMatches[i * 2 + 1]
  108. if a >= 0'i32:
  109. matches[i-1] = bufSubstr(buf, int(a), int(b))
  110. else: matches[i-1] = ""
  111. return rawMatches[1] - rawMatches[0]
  112. proc findBounds*(buf: cstring, pattern: Regex, matches: var openArray[string],
  113. start = 0, bufSize: int): tuple[first, last: int] =
  114. ## returns the starting position and end position of ``pattern`` in ``buf``
  115. ## (where ``buf`` has length ``bufSize`` and is not necessarily ``'\0'`` terminated),
  116. ## and the captured
  117. ## substrings in the array ``matches``. If it does not match, nothing
  118. ## is written into ``matches`` and ``(-1,0)`` is returned.
  119. var
  120. rtarray = initRtArray[cint]((matches.len+1)*3)
  121. rawMatches = rtarray.getRawData
  122. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  123. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  124. if res < 0'i32: return (-1, 0)
  125. for i in 1..int(res)-1:
  126. var a = rawMatches[i * 2]
  127. var b = rawMatches[i * 2 + 1]
  128. if a >= 0'i32: matches[i-1] = bufSubstr(buf, int(a), int(b))
  129. else: matches[i-1] = ""
  130. return (rawMatches[0].int, rawMatches[1].int - 1)
  131. proc findBounds*(s: string, pattern: Regex, matches: var openArray[string],
  132. start = 0): tuple[first, last: int] {.inline.} =
  133. ## returns the starting position and end position of ``pattern`` in ``s``
  134. ## and the captured substrings in the array ``matches``.
  135. ## If it does not match, nothing
  136. ## is written into ``matches`` and ``(-1,0)`` is returned.
  137. result = findBounds(cstring(s), pattern, matches, start, s.len)
  138. proc findBounds*(buf: cstring, pattern: Regex,
  139. matches: var openArray[tuple[first, last: int]],
  140. start = 0, bufSize = 0): tuple[first, last: int] =
  141. ## returns the starting position and end position of ``pattern`` in ``buf``
  142. ## (where ``buf`` has length ``bufSize`` and is not necessarily ``'\0'`` terminated),
  143. ## and the captured substrings in the array ``matches``.
  144. ## If it does not match, nothing is written into ``matches`` and
  145. ## ``(-1,0)`` is returned.
  146. var
  147. rtarray = initRtArray[cint]((matches.len+1)*3)
  148. rawMatches = rtarray.getRawData
  149. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  150. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  151. if res < 0'i32: return (-1, 0)
  152. for i in 1..int(res)-1:
  153. var a = rawMatches[i * 2]
  154. var b = rawMatches[i * 2 + 1]
  155. if a >= 0'i32: matches[i-1] = (int(a), int(b)-1)
  156. else: matches[i-1] = (-1,0)
  157. return (rawMatches[0].int, rawMatches[1].int - 1)
  158. proc findBounds*(s: string, pattern: Regex,
  159. matches: var openArray[tuple[first, last: int]],
  160. start = 0): tuple[first, last: int] {.inline.} =
  161. ## returns the starting position and end position of ``pattern`` in ``s``
  162. ## and the captured substrings in the array ``matches``.
  163. ## If it does not match, nothing is written into ``matches`` and
  164. ## ``(-1,0)`` is returned.
  165. result = findBounds(cstring(s), pattern, matches, start, s.len)
  166. proc findBounds*(buf: cstring, pattern: Regex,
  167. start = 0, bufSize: int): tuple[first, last: int] =
  168. ## returns the ``first`` and ``last`` position of ``pattern`` in ``buf``,
  169. ## where ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  170. ## If it does not match, ``(-1,0)`` is returned.
  171. var
  172. rtarray = initRtArray[cint](3)
  173. rawMatches = rtarray.getRawData
  174. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  175. cast[ptr cint](rawMatches), 3)
  176. if res < 0'i32: return (int(res), 0)
  177. return (int(rawMatches[0]), int(rawMatches[1]-1))
  178. proc findBounds*(s: string, pattern: Regex,
  179. start = 0): tuple[first, last: int] {.inline.} =
  180. ## returns the ``first`` and ``last`` position of ``pattern`` in ``s``.
  181. ## If it does not match, ``(-1,0)`` is returned.
  182. ##
  183. ## Note: there is a speed improvement if the matches do not need to be captured.
  184. ##
  185. ## Example:
  186. ##
  187. ## .. code-block:: nim
  188. ## assert findBounds("01234abc89", re"abc") == (5,7)
  189. result = findBounds(cstring(s), pattern, start, s.len)
  190. proc matchOrFind(buf: cstring, pattern: Regex, start, bufSize: int, flags: cint): cint =
  191. var
  192. rtarray = initRtArray[cint](3)
  193. rawMatches = rtarray.getRawData
  194. result = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, flags,
  195. cast[ptr cint](rawMatches), 3)
  196. if result >= 0'i32:
  197. result = rawMatches[1] - rawMatches[0]
  198. proc matchLen*(s: string, pattern: Regex, matches: var openArray[string],
  199. start = 0): int {.inline.} =
  200. ## the same as ``match``, but it returns the length of the match,
  201. ## if there is no match, ``-1`` is returned. Note that a match length
  202. ## of zero can happen.
  203. result = matchOrFind(cstring(s), pattern, matches, start.cint, s.len.cint, pcre.ANCHORED)
  204. proc matchLen*(buf: cstring, pattern: Regex, matches: var openArray[string],
  205. start = 0, bufSize: int): int {.inline.} =
  206. ## the same as ``match``, but it returns the length of the match,
  207. ## if there is no match, ``-1`` is returned. Note that a match length
  208. ## of zero can happen.
  209. return matchOrFind(buf, pattern, matches, start.cint, bufSize.cint, pcre.ANCHORED)
  210. proc matchLen*(s: string, pattern: Regex, start = 0): int {.inline.} =
  211. ## the same as ``match``, but it returns the length of the match,
  212. ## if there is no match, ``-1`` is returned. Note that a match length
  213. ## of zero can happen.
  214. ##
  215. ## Example:
  216. ##
  217. ## .. code-block:: nim
  218. ## echo matchLen("abcdefg", re"cde", 2) # => 3
  219. ## echo matchLen("abcdefg", re"abcde") # => 5
  220. ## echo matchLen("abcdefg", re"cde") # => -1
  221. result = matchOrFind(cstring(s), pattern, start.cint, s.len.cint, pcre.ANCHORED)
  222. proc matchLen*(buf: cstring, pattern: Regex, start = 0, bufSize: int): int {.inline.} =
  223. ## the same as ``match``, but it returns the length of the match,
  224. ## if there is no match, ``-1`` is returned. Note that a match length
  225. ## of zero can happen.
  226. result = matchOrFind(buf, pattern, start.cint, bufSize, pcre.ANCHORED)
  227. proc match*(s: string, pattern: Regex, start = 0): bool {.inline.} =
  228. ## returns ``true`` if ``s[start..]`` matches the ``pattern``.
  229. result = matchLen(cstring(s), pattern, start, s.len) != -1
  230. proc match*(s: string, pattern: Regex, matches: var openArray[string],
  231. start = 0): bool {.inline.} =
  232. ## returns ``true`` if ``s[start..]`` matches the ``pattern`` and
  233. ## the captured substrings in the array ``matches``. If it does not
  234. ## match, nothing is written into ``matches`` and ``false`` is
  235. ## returned.
  236. ##
  237. ## Example:
  238. ##
  239. ## .. code-block:: nim
  240. ## var matches: array[2, string]
  241. ## if match("abcdefg", re"c(d)ef(g)", matches, 2):
  242. ## for s in matches:
  243. ## echo s # => d g
  244. result = matchLen(cstring(s), pattern, matches, start, s.len) != -1
  245. proc match*(buf: cstring, pattern: Regex, matches: var openArray[string],
  246. start = 0, bufSize: int): bool {.inline.} =
  247. ## returns ``true`` if ``buf[start..<bufSize]`` matches the ``pattern`` and
  248. ## the captured substrings in the array ``matches``. If it does not
  249. ## match, nothing is written into ``matches`` and ``false`` is
  250. ## returned.
  251. ## ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  252. result = matchLen(buf, pattern, matches, start, bufSize) != -1
  253. proc find*(buf: cstring, pattern: Regex, matches: var openArray[string],
  254. start = 0, bufSize = 0): int =
  255. ## returns the starting position of ``pattern`` in ``buf`` and the captured
  256. ## substrings in the array ``matches``. If it does not match, nothing
  257. ## is written into ``matches`` and ``-1`` is returned.
  258. ## ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  259. var
  260. rtarray = initRtArray[cint]((matches.len+1)*3)
  261. rawMatches = rtarray.getRawData
  262. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  263. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  264. if res < 0'i32: return res
  265. for i in 1..int(res)-1:
  266. var a = rawMatches[i * 2]
  267. var b = rawMatches[i * 2 + 1]
  268. if a >= 0'i32: matches[i-1] = bufSubstr(buf, int(a), int(b))
  269. else: matches[i-1] = ""
  270. return rawMatches[0]
  271. proc find*(s: string, pattern: Regex, matches: var openArray[string],
  272. start = 0): int {.inline.} =
  273. ## returns the starting position of ``pattern`` in ``s`` and the captured
  274. ## substrings in the array ``matches``. If it does not match, nothing
  275. ## is written into ``matches`` and ``-1`` is returned.
  276. result = find(cstring(s), pattern, matches, start, s.len)
  277. proc find*(buf: cstring, pattern: Regex, start = 0, bufSize: int): int =
  278. ## returns the starting position of ``pattern`` in ``buf``,
  279. ## where ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  280. ## If it does not match, ``-1`` is returned.
  281. var
  282. rtarray = initRtArray[cint](3)
  283. rawMatches = rtarray.getRawData
  284. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  285. cast[ptr cint](rawMatches), 3)
  286. if res < 0'i32: return res
  287. return rawMatches[0]
  288. proc find*(s: string, pattern: Regex, start = 0): int {.inline.} =
  289. ## returns the starting position of ``pattern`` in ``s``. If it does not
  290. ## match, ``-1`` is returned.
  291. ##
  292. ## Example:
  293. ##
  294. ## .. code-block:: nim
  295. ## echo find("abcdefg", re"cde") # => 2
  296. ## echo find("abcdefg", re"abc") # => 0
  297. ## echo find("abcdefg", re"zz") # => -1
  298. result = find(cstring(s), pattern, start, s.len)
  299. iterator findAll*(s: string, pattern: Regex, start = 0): string =
  300. ## Yields all matching *substrings* of `s` that match `pattern`.
  301. ##
  302. ## Note that since this is an iterator you should not modify the string you
  303. ## are iterating over: bad things could happen.
  304. var
  305. i = int32(start)
  306. rtarray = initRtArray[cint](3)
  307. rawMatches = rtarray.getRawData
  308. while true:
  309. let res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, i, 0'i32,
  310. cast[ptr cint](rawMatches), 3)
  311. if res < 0'i32: break
  312. let a = rawMatches[0]
  313. let b = rawMatches[1]
  314. if a == b and a == i: break
  315. yield substr(s, int(a), int(b)-1)
  316. i = b
  317. iterator findAll*(buf: cstring, pattern: Regex, start = 0, bufSize: int): string =
  318. ## Yields all matching `substrings` of ``s`` that match ``pattern``.
  319. ##
  320. ## Note that since this is an iterator you should not modify the string you
  321. ## are iterating over: bad things could happen.
  322. var
  323. i = int32(start)
  324. rtarray = initRtArray[cint](3)
  325. rawMatches = rtarray.getRawData
  326. while true:
  327. let res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, i, 0'i32,
  328. cast[ptr cint](rawMatches), 3)
  329. if res < 0'i32: break
  330. let a = rawMatches[0]
  331. let b = rawMatches[1]
  332. if a == b and a == i: break
  333. var str = newString(b-a)
  334. copyMem(str[0].addr, unsafeAddr(buf[a]), b-a)
  335. yield str
  336. i = b
  337. proc findAll*(s: string, pattern: Regex, start = 0): seq[string] {.inline.} =
  338. ## returns all matching `substrings` of ``s`` that match ``pattern``.
  339. ## If it does not match, @[] is returned.
  340. result = @[]
  341. for x in findAll(s, pattern, start): result.add x
  342. when not defined(nimhygiene):
  343. {.pragma: inject.}
  344. template `=~` *(s: string, pattern: Regex): untyped =
  345. ## This calls ``match`` with an implicit declared ``matches`` array that
  346. ## can be used in the scope of the ``=~`` call:
  347. ##
  348. ## .. code-block:: nim
  349. ##
  350. ## if line =~ re"\s*(\w+)\s*\=\s*(\w+)":
  351. ## # matches a key=value pair:
  352. ## echo("Key: ", matches[0])
  353. ## echo("Value: ", matches[1])
  354. ## elif line =~ re"\s*(\#.*)":
  355. ## # matches a comment
  356. ## # note that the implicit ``matches`` array is different from the
  357. ## # ``matches`` array of the first branch
  358. ## echo("comment: ", matches[0])
  359. ## else:
  360. ## echo("syntax error")
  361. ##
  362. bind MaxSubpatterns
  363. when not declaredInScope(matches):
  364. var matches {.inject.}: array[MaxSubpatterns, string]
  365. match(s, pattern, matches)
  366. # ------------------------- more string handling ------------------------------
  367. proc contains*(s: string, pattern: Regex, start = 0): bool {.inline.} =
  368. ## same as ``find(s, pattern, start) >= 0``
  369. return find(s, pattern, start) >= 0
  370. proc contains*(s: string, pattern: Regex, matches: var openArray[string],
  371. start = 0): bool {.inline.} =
  372. ## same as ``find(s, pattern, matches, start) >= 0``
  373. return find(s, pattern, matches, start) >= 0
  374. proc startsWith*(s: string, prefix: Regex): bool {.inline.} =
  375. ## returns true if `s` starts with the pattern `prefix`
  376. result = matchLen(s, prefix) >= 0
  377. proc endsWith*(s: string, suffix: Regex): bool {.inline.} =
  378. ## returns true if `s` ends with the pattern `suffix`
  379. for i in 0 .. s.len-1:
  380. if matchLen(s, suffix, i) == s.len - i: return true
  381. proc replace*(s: string, sub: Regex, by = ""): string =
  382. ## Replaces ``sub`` in ``s`` by the string ``by``. Captures cannot be
  383. ## accessed in ``by``.
  384. ##
  385. ## Example:
  386. ##
  387. ## .. code-block:: nim
  388. ## "var1=key; var2=key2".replace(re"(\w+)=(\w+)")
  389. ##
  390. ## Results in:
  391. ##
  392. ## .. code-block:: nim
  393. ##
  394. ## "; "
  395. result = ""
  396. var prev = 0
  397. while prev < s.len:
  398. var match = findBounds(s, sub, prev)
  399. if match.first < 0: break
  400. add(result, substr(s, prev, match.first-1))
  401. add(result, by)
  402. if match.last + 1 == prev: break
  403. prev = match.last + 1
  404. add(result, substr(s, prev))
  405. proc replacef*(s: string, sub: Regex, by: string): string =
  406. ## Replaces ``sub`` in ``s`` by the string ``by``. Captures can be accessed in ``by``
  407. ## with the notation ``$i`` and ``$#`` (see strutils.\`%\`).
  408. ##
  409. ## Example:
  410. ##
  411. ## .. code-block:: nim
  412. ## "var1=key; var2=key2".replacef(re"(\w+)=(\w+)", "$1<-$2$2")
  413. ##
  414. ## Results in:
  415. ##
  416. ## .. code-block:: nim
  417. ##
  418. ## "var1<-keykey; var2<-key2key2"
  419. result = ""
  420. var caps: array[MaxSubpatterns, string]
  421. var prev = 0
  422. while prev < s.len:
  423. var match = findBounds(s, sub, caps, prev)
  424. if match.first < 0: break
  425. add(result, substr(s, prev, match.first-1))
  426. addf(result, by, caps)
  427. if match.last + 1 == prev: break
  428. prev = match.last + 1
  429. add(result, substr(s, prev))
  430. proc multiReplace*(s: string, subs: openArray[
  431. tuple[pattern: Regex, repl: string]]): string =
  432. ## Returns a modified copy of ``s`` with the substitutions in ``subs``
  433. ## applied in parallel.
  434. result = ""
  435. var i = 0
  436. var caps: array[MaxSubpatterns, string]
  437. while i < s.len:
  438. block searchSubs:
  439. for j in 0..high(subs):
  440. var x = matchLen(s, subs[j][0], caps, i)
  441. if x > 0:
  442. addf(result, subs[j][1], caps)
  443. inc(i, x)
  444. break searchSubs
  445. add(result, s[i])
  446. inc(i)
  447. # copy the rest:
  448. add(result, substr(s, i))
  449. proc parallelReplace*(s: string, subs: openArray[
  450. tuple[pattern: Regex, repl: string]]): string {.deprecated:
  451. "Deprecated since v0.18.0: Use ``multiReplace`` instead.".} =
  452. ## Returns a modified copy of ``s`` with the substitutions in ``subs``
  453. ## applied in parallel.
  454. result = multiReplace(s, subs)
  455. proc transformFile*(infile, outfile: string,
  456. subs: openArray[tuple[pattern: Regex, repl: string]]) =
  457. ## reads in the file ``infile``, performs a parallel replacement (calls
  458. ## ``parallelReplace``) and writes back to ``outfile``. Raises ``IOError`` if an
  459. ## error occurs. This is supposed to be used for quick scripting.
  460. var x = readFile(infile).string
  461. writeFile(outfile, x.multiReplace(subs))
  462. iterator split*(s: string, sep: Regex; maxsplit = -1): string =
  463. ## Splits the string ``s`` into substrings.
  464. ##
  465. ## Substrings are separated by the regular expression ``sep``
  466. ## (and the portion matched by ``sep`` is not returned).
  467. ##
  468. ## Example:
  469. ##
  470. ## .. code-block:: nim
  471. ## for word in split("00232this02939is39an22example111", re"\d+"):
  472. ## writeLine(stdout, word)
  473. ##
  474. ## Results in:
  475. ##
  476. ## .. code-block:: nim
  477. ## ""
  478. ## "this"
  479. ## "is"
  480. ## "an"
  481. ## "example"
  482. ## ""
  483. ##
  484. var last = 0
  485. var splits = maxsplit
  486. var x: int
  487. while last <= len(s):
  488. var first = last
  489. var sepLen = 1
  490. while last < len(s):
  491. x = matchLen(s, sep, last)
  492. if x >= 0:
  493. sepLen = x
  494. break
  495. inc(last)
  496. if x == 0:
  497. if last >= len(s): break
  498. inc last
  499. if splits == 0: last = len(s)
  500. yield substr(s, first, last-1)
  501. if splits == 0: break
  502. dec(splits)
  503. inc(last, sepLen)
  504. proc split*(s: string, sep: Regex, maxsplit = -1): seq[string] {.inline.} =
  505. ## Splits the string ``s`` into a seq of substrings.
  506. ##
  507. ## The portion matched by ``sep`` is not returned.
  508. result = @[]
  509. for x in split(s, sep, maxsplit): result.add x
  510. proc escapeRe*(s: string): string =
  511. ## escapes ``s`` so that it is matched verbatim when used as a regular
  512. ## expression.
  513. result = ""
  514. for c in items(s):
  515. case c
  516. of 'a'..'z', 'A'..'Z', '0'..'9', '_':
  517. result.add(c)
  518. else:
  519. result.add("\\x")
  520. result.add(toHex(ord(c), 2))
  521. when isMainModule:
  522. doAssert match("(a b c)", rex"\( .* \)")
  523. doAssert match("WHiLe", re("while", {reIgnoreCase}))
  524. doAssert "0158787".match(re"\d+")
  525. doAssert "ABC 0232".match(re"\w+\s+\d+")
  526. doAssert "ABC".match(rex"\d+ | \w+")
  527. {.push warnings:off.}
  528. doAssert matchLen("key", re"\b[a-zA-Z_]+[a-zA-Z_0-9]*\b") == 3
  529. {.pop.}
  530. var pattern = re"[a-z0-9]+\s*=\s*[a-z0-9]+"
  531. doAssert matchLen("key1= cal9", pattern) == 11
  532. doAssert find("_____abc_______", re"abc") == 5
  533. doAssert findBounds("_____abc_______", re"abc") == (5,7)
  534. var matches: array[6, string]
  535. if match("abcdefg", re"c(d)ef(g)", matches, 2):
  536. doAssert matches[0] == "d"
  537. doAssert matches[1] == "g"
  538. else:
  539. doAssert false
  540. if "abc" =~ re"(a)bcxyz|(\w+)":
  541. doAssert matches[1] == "abc"
  542. else:
  543. doAssert false
  544. if "abc" =~ re"(cba)?.*":
  545. doAssert matches[0] == ""
  546. else: doAssert false
  547. if "abc" =~ re"().*":
  548. doAssert matches[0] == ""
  549. else: doAssert false
  550. doAssert "var1=key; var2=key2".endsWith(re"\w+=\w+")
  551. doAssert("var1=key; var2=key2".replacef(re"(\w+)=(\w+)", "$1<-$2$2") ==
  552. "var1<-keykey; var2<-key2key2")
  553. doAssert("var1=key; var2=key2".replace(re"(\w+)=(\w+)", "$1<-$2$2") ==
  554. "$1<-$2$2; $1<-$2$2")
  555. var accum: seq[string] = @[]
  556. for word in split("00232this02939is39an22example111", re"\d+"):
  557. accum.add(word)
  558. doAssert(accum == @["", "this", "is", "an", "example", ""])
  559. accum = @[]
  560. for word in split("00232this02939is39an22example111", re"\d+", maxsplit=2):
  561. accum.add(word)
  562. doAssert(accum == @["", "this", "is39an22example111"])
  563. accum = @[]
  564. for word in split("AAA : : BBB", re"\s*:\s*"):
  565. accum.add(word)
  566. doAssert(accum == @["AAA", "", "BBB"])
  567. doAssert(split("abc", re"") == @["a", "b", "c"])
  568. doAssert(split("", re"") == @[])
  569. doAssert(split("a;b;c", re";") == @["a", "b", "c"])
  570. doAssert(split(";a;b;c", re";") == @["", "a", "b", "c"])
  571. doAssert(split(";a;b;c;", re";") == @["", "a", "b", "c", ""])
  572. doAssert(split("a;b;c;", re";") == @["a", "b", "c", ""])
  573. doAssert(split("00232this02939is39an22example111", re"\d+", maxsplit=2) == @["", "this", "is39an22example111"])
  574. for x in findAll("abcdef", re"^{.}", 3):
  575. doAssert x == "d"
  576. accum = @[]
  577. for x in findAll("abcdef", re".", 3):
  578. accum.add(x)
  579. doAssert(accum == @["d", "e", "f"])
  580. doAssert("XYZ".find(re"^\d*") == 0)
  581. doAssert("XYZ".match(re"^\d*") == true)
  582. block:
  583. var matches: array[16, string]
  584. if match("abcdefghijklmnop", re"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)", matches):
  585. for i in 0..matches.high:
  586. doAssert matches[i] == $chr(i + 'a'.ord)
  587. else:
  588. doAssert false
  589. block: # Buffer based RE
  590. var cs: cstring = "_____abc_______"
  591. doAssert(cs.find(re"abc", bufSize=15) == 5)
  592. doAssert(cs.matchLen(re"_*abc", bufSize=15) == 8)
  593. doAssert(cs.matchLen(re"abc", start=5, bufSize=15) == 3)
  594. doAssert(cs.matchLen(re"abc", start=5, bufSize=7) == -1)
  595. doAssert(cs.matchLen(re"abc_*", start=5, bufSize=10) == 5)
  596. var accum: seq[string] = @[]
  597. for x in cs.findAll(re"[a-z]", start=3, bufSize=15):
  598. accum.add($x)
  599. doAssert(accum == @["a","b","c"])
  600. block:
  601. # bug #9306
  602. doAssert replace("bar", re"^", "foo") == "foobar"
  603. doAssert replace("foo", re"", "-") == "-foo"
  604. doAssert replace("foo", re"$", "bar") == "foobar"