re.nim 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. when defined(js):
  10. {.error: "This library needs to be compiled with a c-like backend, and depends on PCRE; See jsre for JS backend.".}
  11. ## Regular expression support for Nim.
  12. ##
  13. ## This module is implemented by providing a wrapper around the
  14. ## `PCRE (Perl-Compatible Regular Expressions) <http://www.pcre.org>`_
  15. ## C library. This means that your application will depend on the PCRE
  16. ## library's licence when using this module, which should not be a problem
  17. ## though.
  18. ## PCRE's licence follows:
  19. ##
  20. ## .. include:: ../../doc/regexprs.txt
  21. ##
  22. runnableExamples:
  23. ## Unless specified otherwise, `start` parameter in each proc indicates
  24. ## where the scan starts, but outputs are relative to the start of the input
  25. ## string, not to `start`:
  26. doAssert find("uxabc", re"(?<=x|y)ab", start = 1) == 2 # lookbehind assertion
  27. doAssert find("uxabc", re"ab", start = 3) == -1 # we're past `start` => not found
  28. doAssert not match("xabc", re"^abc$", start = 1)
  29. # can't match start of string since we're starting at 1
  30. import
  31. pcre, strutils, rtarrays
  32. const
  33. MaxSubpatterns* = 20
  34. ## defines the maximum number of subpatterns that can be captured.
  35. ## This limit still exists for ``replacef`` and ``parallelReplace``.
  36. type
  37. RegexFlag* = enum ## options for regular expressions
  38. reIgnoreCase = 0, ## do caseless matching
  39. reMultiLine = 1, ## ``^`` and ``$`` match newlines within data
  40. reDotAll = 2, ## ``.`` matches anything including NL
  41. reExtended = 3, ## ignore whitespace and ``#`` comments
  42. reStudy = 4 ## study the expression (may be omitted if the
  43. ## expression will be used only once)
  44. RegexDesc = object
  45. h: ptr Pcre
  46. e: ptr ExtraData
  47. Regex* = ref RegexDesc ## a compiled regular expression
  48. RegexError* = object of ValueError
  49. ## is raised if the pattern is no valid regular expression.
  50. when defined(gcDestructors):
  51. proc `=destroy`(x: var RegexDesc) =
  52. pcre.free_substring(cast[cstring](x.h))
  53. if not isNil(x.e):
  54. pcre.free_study(x.e)
  55. proc raiseInvalidRegex(msg: string) {.noinline, noreturn.} =
  56. var e: ref RegexError
  57. new(e)
  58. e.msg = msg
  59. raise e
  60. proc rawCompile(pattern: string, flags: cint): ptr Pcre =
  61. var
  62. msg: cstring = ""
  63. offset: cint = 0
  64. result = pcre.compile(pattern, flags, addr(msg), addr(offset), nil)
  65. if result == nil:
  66. raiseInvalidRegex($msg & "\n" & pattern & "\n" & spaces(offset) & "^\n")
  67. proc finalizeRegEx(x: Regex) =
  68. # XXX This is a hack, but PCRE does not export its "free" function properly.
  69. # Sigh. The hack relies on PCRE's implementation (see ``pcre_get.c``).
  70. # Fortunately the implementation is unlikely to change.
  71. pcre.free_substring(cast[cstring](x.h))
  72. if not isNil(x.e):
  73. pcre.free_study(x.e)
  74. proc re*(s: string, flags = {reStudy}): Regex =
  75. ## Constructor of regular expressions.
  76. ##
  77. ## Note that Nim's
  78. ## extended raw string literals support the syntax ``re"[abc]"`` as
  79. ## a short form for ``re(r"[abc]")``. Also note that since this
  80. ## compiles the regular expression, which is expensive, you should
  81. ## avoid putting it directly in the arguments of the functions like
  82. ## the examples show below if you plan to use it a lot of times, as
  83. ## this will hurt performance immensely. (e.g. outside a loop, ...)
  84. when defined(gcDestructors):
  85. result = Regex()
  86. else:
  87. new(result, finalizeRegEx)
  88. result.h = rawCompile(s, cast[cint](flags - {reStudy}))
  89. if reStudy in flags:
  90. var msg: cstring = ""
  91. var options: cint = 0
  92. var hasJit: cint = 0
  93. if pcre.config(pcre.CONFIG_JIT, addr hasJit) == 0:
  94. if hasJit == 1'i32:
  95. options = pcre.STUDY_JIT_COMPILE
  96. result.e = pcre.study(result.h, options, addr msg)
  97. if not isNil(msg): raiseInvalidRegex($msg)
  98. proc rex*(s: string, flags = {reStudy, reExtended}): Regex =
  99. ## Constructor for extended regular expressions.
  100. ##
  101. ## The extended means that comments starting with `#` and
  102. ## whitespace are ignored.
  103. result = re(s, flags)
  104. proc bufSubstr(b: cstring, sPos, ePos: int): string {.inline.} =
  105. ## Return a Nim string built from a slice of a cstring buffer.
  106. ## Don't assume cstring is '\0' terminated
  107. let sz = ePos - sPos
  108. result = newString(sz+1)
  109. copyMem(addr(result[0]), unsafeAddr(b[sPos]), sz)
  110. result.setLen(sz)
  111. proc matchOrFind(buf: cstring, pattern: Regex, matches: var openArray[string],
  112. start, bufSize, flags: cint): cint =
  113. var
  114. rtarray = initRtArray[cint]((matches.len+1)*3)
  115. rawMatches = rtarray.getRawData
  116. res = pcre.exec(pattern.h, pattern.e, buf, bufSize, start, flags,
  117. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  118. if res < 0'i32: return res
  119. for i in 1..int(res)-1:
  120. var a = rawMatches[i * 2]
  121. var b = rawMatches[i * 2 + 1]
  122. if a >= 0'i32:
  123. matches[i-1] = bufSubstr(buf, int(a), int(b))
  124. else: matches[i-1] = ""
  125. return rawMatches[1] - rawMatches[0]
  126. proc findBounds*(buf: cstring, pattern: Regex, matches: var openArray[string],
  127. start = 0, bufSize: int): tuple[first, last: int] =
  128. ## returns the starting position and end position of ``pattern`` in ``buf``
  129. ## (where ``buf`` has length ``bufSize`` and is not necessarily ``'\0'`` terminated),
  130. ## and the captured
  131. ## substrings in the array ``matches``. If it does not match, nothing
  132. ## is written into ``matches`` and ``(-1,0)`` is returned.
  133. var
  134. rtarray = initRtArray[cint]((matches.len+1)*3)
  135. rawMatches = rtarray.getRawData
  136. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  137. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  138. if res < 0'i32: return (-1, 0)
  139. for i in 1..int(res)-1:
  140. var a = rawMatches[i * 2]
  141. var b = rawMatches[i * 2 + 1]
  142. if a >= 0'i32: matches[i-1] = bufSubstr(buf, int(a), int(b))
  143. else: matches[i-1] = ""
  144. return (rawMatches[0].int, rawMatches[1].int - 1)
  145. proc findBounds*(s: string, pattern: Regex, matches: var openArray[string],
  146. start = 0): tuple[first, last: int] {.inline.} =
  147. ## returns the starting position and end position of ``pattern`` in ``s``
  148. ## and the captured substrings in the array ``matches``.
  149. ## If it does not match, nothing
  150. ## is written into ``matches`` and ``(-1,0)`` is returned.
  151. result = findBounds(cstring(s), pattern, matches, start, s.len)
  152. proc findBounds*(buf: cstring, pattern: Regex,
  153. matches: var openArray[tuple[first, last: int]],
  154. start = 0, bufSize = 0): tuple[first, last: int] =
  155. ## returns the starting position and end position of ``pattern`` in ``buf``
  156. ## (where ``buf`` has length ``bufSize`` and is not necessarily ``'\0'`` terminated),
  157. ## and the captured substrings in the array ``matches``.
  158. ## If it does not match, nothing is written into ``matches`` and
  159. ## ``(-1,0)`` is returned.
  160. var
  161. rtarray = initRtArray[cint]((matches.len+1)*3)
  162. rawMatches = rtarray.getRawData
  163. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  164. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  165. if res < 0'i32: return (-1, 0)
  166. for i in 1..int(res)-1:
  167. var a = rawMatches[i * 2]
  168. var b = rawMatches[i * 2 + 1]
  169. if a >= 0'i32: matches[i-1] = (int(a), int(b)-1)
  170. else: matches[i-1] = (-1,0)
  171. return (rawMatches[0].int, rawMatches[1].int - 1)
  172. proc findBounds*(s: string, pattern: Regex,
  173. matches: var openArray[tuple[first, last: int]],
  174. start = 0): tuple[first, last: int] {.inline.} =
  175. ## returns the starting position and end position of ``pattern`` in ``s``
  176. ## and the captured substrings in the array ``matches``.
  177. ## If it does not match, nothing is written into ``matches`` and
  178. ## ``(-1,0)`` is returned.
  179. result = findBounds(cstring(s), pattern, matches, start, s.len)
  180. proc findBounds*(buf: cstring, pattern: Regex,
  181. start = 0, bufSize: int): tuple[first, last: int] =
  182. ## returns the ``first`` and ``last`` position of ``pattern`` in ``buf``,
  183. ## where ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  184. ## If it does not match, ``(-1,0)`` is returned.
  185. var
  186. rtarray = initRtArray[cint](3)
  187. rawMatches = rtarray.getRawData
  188. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  189. cast[ptr cint](rawMatches), 3)
  190. if res < 0'i32: return (int(res), 0)
  191. return (int(rawMatches[0]), int(rawMatches[1]-1))
  192. proc findBounds*(s: string, pattern: Regex,
  193. start = 0): tuple[first, last: int] {.inline.} =
  194. ## returns the ``first`` and ``last`` position of ``pattern`` in ``s``.
  195. ## If it does not match, ``(-1,0)`` is returned.
  196. ##
  197. ## Note: there is a speed improvement if the matches do not need to be captured.
  198. runnableExamples:
  199. assert findBounds("01234abc89", re"abc") == (5,7)
  200. result = findBounds(cstring(s), pattern, start, s.len)
  201. proc matchOrFind(buf: cstring, pattern: Regex, start, bufSize: int, flags: cint): cint =
  202. var
  203. rtarray = initRtArray[cint](3)
  204. rawMatches = rtarray.getRawData
  205. result = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, flags,
  206. cast[ptr cint](rawMatches), 3)
  207. if result >= 0'i32:
  208. result = rawMatches[1] - rawMatches[0]
  209. proc matchLen*(s: string, pattern: Regex, matches: var openArray[string],
  210. 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. result = matchOrFind(cstring(s), pattern, matches, start.cint, s.len.cint, pcre.ANCHORED)
  215. proc matchLen*(buf: cstring, pattern: Regex, matches: var openArray[string],
  216. start = 0, bufSize: int): int {.inline.} =
  217. ## the same as ``match``, but it returns the length of the match,
  218. ## if there is no match, ``-1`` is returned. Note that a match length
  219. ## of zero can happen.
  220. return matchOrFind(buf, pattern, matches, start.cint, bufSize.cint, pcre.ANCHORED)
  221. proc matchLen*(s: string, pattern: Regex, start = 0): int {.inline.} =
  222. ## the same as ``match``, but it returns the length of the match,
  223. ## if there is no match, ``-1`` is returned. Note that a match length
  224. ## of zero can happen.
  225. ##
  226. runnableExamples:
  227. doAssert matchLen("abcdefg", re"cde", 2) == 3
  228. doAssert matchLen("abcdefg", re"abcde") == 5
  229. doAssert matchLen("abcdefg", re"cde") == -1
  230. result = matchOrFind(cstring(s), pattern, start.cint, s.len.cint, pcre.ANCHORED)
  231. proc matchLen*(buf: cstring, pattern: Regex, start = 0, bufSize: int): int {.inline.} =
  232. ## the same as ``match``, but it returns the length of the match,
  233. ## if there is no match, ``-1`` is returned. Note that a match length
  234. ## of zero can happen.
  235. result = matchOrFind(buf, pattern, start.cint, bufSize, pcre.ANCHORED)
  236. proc match*(s: string, pattern: Regex, start = 0): bool {.inline.} =
  237. ## returns ``true`` if ``s[start..]`` matches the ``pattern``.
  238. result = matchLen(cstring(s), pattern, start, s.len) != -1
  239. proc match*(s: string, pattern: Regex, matches: var openArray[string],
  240. start = 0): bool {.inline.} =
  241. ## returns ``true`` if ``s[start..]`` matches the ``pattern`` and
  242. ## the captured substrings in the array ``matches``. If it does not
  243. ## match, nothing is written into ``matches`` and ``false`` is
  244. ## returned.
  245. ##
  246. runnableExamples:
  247. import sequtils
  248. var matches: array[2, string]
  249. if match("abcdefg", re"c(d)ef(g)", matches, 2):
  250. doAssert toSeq(matches) == @["d", "g"]
  251. result = matchLen(cstring(s), pattern, matches, start, s.len) != -1
  252. proc match*(buf: cstring, pattern: Regex, matches: var openArray[string],
  253. start = 0, bufSize: int): bool {.inline.} =
  254. ## returns ``true`` if ``buf[start..<bufSize]`` matches the ``pattern`` and
  255. ## the captured substrings in the array ``matches``. If it does not
  256. ## match, nothing is written into ``matches`` and ``false`` is
  257. ## returned.
  258. ## ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  259. result = matchLen(buf, pattern, matches, start, bufSize) != -1
  260. proc find*(buf: cstring, pattern: Regex, matches: var openArray[string],
  261. start = 0, bufSize = 0): int =
  262. ## returns the starting position of ``pattern`` in ``buf`` and the captured
  263. ## substrings in the array ``matches``. If it does not match, nothing
  264. ## is written into ``matches`` and ``-1`` is returned.
  265. ## ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  266. var
  267. rtarray = initRtArray[cint]((matches.len+1)*3)
  268. rawMatches = rtarray.getRawData
  269. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  270. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  271. if res < 0'i32: return res
  272. for i in 1..int(res)-1:
  273. var a = rawMatches[i * 2]
  274. var b = rawMatches[i * 2 + 1]
  275. if a >= 0'i32: matches[i-1] = bufSubstr(buf, int(a), int(b))
  276. else: matches[i-1] = ""
  277. return rawMatches[0]
  278. proc find*(s: string, pattern: Regex, matches: var openArray[string],
  279. start = 0): int {.inline.} =
  280. ## returns the starting position of ``pattern`` in ``s`` and the captured
  281. ## substrings in the array ``matches``. If it does not match, nothing
  282. ## is written into ``matches`` and ``-1`` is returned.
  283. result = find(cstring(s), pattern, matches, start, s.len)
  284. proc find*(buf: cstring, pattern: Regex, start = 0, bufSize: int): int =
  285. ## returns the starting position of ``pattern`` in ``buf``,
  286. ## where ``buf`` has length ``bufSize`` (not necessarily ``'\0'`` terminated).
  287. ## If it does not match, ``-1`` is returned.
  288. var
  289. rtarray = initRtArray[cint](3)
  290. rawMatches = rtarray.getRawData
  291. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  292. cast[ptr cint](rawMatches), 3)
  293. if res < 0'i32: return res
  294. return rawMatches[0]
  295. proc find*(s: string, pattern: Regex, start = 0): int {.inline.} =
  296. ## returns the starting position of ``pattern`` in ``s``. If it does not
  297. ## match, ``-1`` is returned. We start the scan at `start`.
  298. runnableExamples:
  299. doAssert find("abcdefg", re"cde") == 2
  300. doAssert find("abcdefg", re"abc") == 0
  301. doAssert find("abcdefg", re"zz") == -1 # not found
  302. doAssert find("abcdefg", re"cde", start = 2) == 2 # still 2
  303. doAssert find("abcdefg", re"cde", start = 3) == -1 # we're past the start position
  304. doAssert find("xabc", re"(?<=x|y)abc", start = 1) == 1
  305. # lookbehind assertion `(?<=x|y)` can look behind `start`
  306. result = find(cstring(s), pattern, start, s.len)
  307. iterator findAll*(s: string, pattern: Regex, start = 0): string =
  308. ## Yields all matching *substrings* of `s` that match `pattern`.
  309. ##
  310. ## Note that since this is an iterator you should not modify the string you
  311. ## are iterating over: bad things could happen.
  312. var
  313. i = int32(start)
  314. rtarray = initRtArray[cint](3)
  315. rawMatches = rtarray.getRawData
  316. while true:
  317. let res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, i, 0'i32,
  318. cast[ptr cint](rawMatches), 3)
  319. if res < 0'i32: break
  320. let a = rawMatches[0]
  321. let b = rawMatches[1]
  322. if a == b and a == i: break
  323. yield substr(s, int(a), int(b)-1)
  324. i = b
  325. iterator findAll*(buf: cstring, pattern: Regex, start = 0, bufSize: int): string =
  326. ## Yields all matching `substrings` of ``s`` that match ``pattern``.
  327. ##
  328. ## Note that since this is an iterator you should not modify the string you
  329. ## are iterating over: bad things could happen.
  330. var
  331. i = int32(start)
  332. rtarray = initRtArray[cint](3)
  333. rawMatches = rtarray.getRawData
  334. while true:
  335. let res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, i, 0'i32,
  336. cast[ptr cint](rawMatches), 3)
  337. if res < 0'i32: break
  338. let a = rawMatches[0]
  339. let b = rawMatches[1]
  340. if a == b and a == i: break
  341. var str = newString(b-a)
  342. copyMem(str[0].addr, unsafeAddr(buf[a]), b-a)
  343. yield str
  344. i = b
  345. proc findAll*(s: string, pattern: Regex, start = 0): seq[string] {.inline.} =
  346. ## returns all matching `substrings` of ``s`` that match ``pattern``.
  347. ## If it does not match, @[] is returned.
  348. result = @[]
  349. for x in findAll(s, pattern, start): result.add x
  350. when not defined(nimhygiene):
  351. {.pragma: inject.}
  352. template `=~` *(s: string, pattern: Regex): untyped =
  353. ## This calls ``match`` with an implicit declared ``matches`` array that
  354. ## can be used in the scope of the ``=~`` call:
  355. runnableExamples:
  356. proc parse(line: string): string =
  357. if line =~ re"\s*(\w+)\s*\=\s*(\w+)": # matches a key=value pair:
  358. result = $(matches[0], matches[1])
  359. elif line =~ re"\s*(\#.*)": # matches a comment
  360. # note that the implicit ``matches`` array is different from 1st branch
  361. result = $(matches[0],)
  362. else: doAssert false
  363. doAssert not declared(matches)
  364. doAssert parse("NAME = LENA") == """("NAME", "LENA")"""
  365. doAssert parse(" # comment ... ") == """("# comment ... ",)"""
  366. bind MaxSubpatterns
  367. when not declaredInScope(matches):
  368. var matches {.inject.}: array[MaxSubpatterns, string]
  369. match(s, pattern, matches)
  370. # ------------------------- more string handling ------------------------------
  371. proc contains*(s: string, pattern: Regex, start = 0): bool {.inline.} =
  372. ## same as ``find(s, pattern, start) >= 0``
  373. return find(s, pattern, start) >= 0
  374. proc contains*(s: string, pattern: Regex, matches: var openArray[string],
  375. start = 0): bool {.inline.} =
  376. ## same as ``find(s, pattern, matches, start) >= 0``
  377. return find(s, pattern, matches, start) >= 0
  378. proc startsWith*(s: string, prefix: Regex): bool {.inline.} =
  379. ## returns true if `s` starts with the pattern `prefix`
  380. result = matchLen(s, prefix) >= 0
  381. proc endsWith*(s: string, suffix: Regex): bool {.inline.} =
  382. ## returns true if `s` ends with the pattern `suffix`
  383. for i in 0 .. s.len-1:
  384. if matchLen(s, suffix, i) == s.len - i: return true
  385. proc replace*(s: string, sub: Regex, by = ""): string =
  386. ## Replaces ``sub`` in ``s`` by the string ``by``. Captures cannot be
  387. ## accessed in ``by``.
  388. runnableExamples:
  389. doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)") == "; "
  390. doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)", "?") == "?; ?"
  391. result = ""
  392. var prev = 0
  393. while prev < s.len:
  394. var match = findBounds(s, sub, prev)
  395. if match.first < 0: break
  396. add(result, substr(s, prev, match.first-1))
  397. add(result, by)
  398. if match.last + 1 == prev: break
  399. prev = match.last + 1
  400. add(result, substr(s, prev))
  401. proc replacef*(s: string, sub: Regex, by: string): string =
  402. ## Replaces ``sub`` in ``s`` by the string ``by``. Captures can be accessed in ``by``
  403. ## with the notation ``$i`` and ``$#`` (see strutils.\`%\`).
  404. runnableExamples:
  405. doAssert "var1=key; var2=key2".replacef(re"(\w+)=(\w+)", "$1<-$2$2") ==
  406. "var1<-keykey; var2<-key2key2"
  407. result = ""
  408. var caps: array[MaxSubpatterns, string]
  409. var prev = 0
  410. while prev < s.len:
  411. var match = findBounds(s, sub, caps, prev)
  412. if match.first < 0: break
  413. add(result, substr(s, prev, match.first-1))
  414. addf(result, by, caps)
  415. if match.last + 1 == prev: break
  416. prev = match.last + 1
  417. add(result, substr(s, prev))
  418. proc multiReplace*(s: string, subs: openArray[
  419. tuple[pattern: Regex, repl: string]]): string =
  420. ## Returns a modified copy of ``s`` with the substitutions in ``subs``
  421. ## applied in parallel.
  422. result = ""
  423. var i = 0
  424. var caps: array[MaxSubpatterns, string]
  425. while i < s.len:
  426. block searchSubs:
  427. for j in 0..high(subs):
  428. var x = matchLen(s, subs[j][0], caps, i)
  429. if x > 0:
  430. addf(result, subs[j][1], caps)
  431. inc(i, x)
  432. break searchSubs
  433. add(result, s[i])
  434. inc(i)
  435. # copy the rest:
  436. add(result, substr(s, i))
  437. proc transformFile*(infile, outfile: string,
  438. subs: openArray[tuple[pattern: Regex, repl: string]]) =
  439. ## reads in the file ``infile``, performs a parallel replacement (calls
  440. ## ``parallelReplace``) and writes back to ``outfile``. Raises ``IOError`` if an
  441. ## error occurs. This is supposed to be used for quick scripting.
  442. var x = readFile(infile).string
  443. writeFile(outfile, x.multiReplace(subs))
  444. iterator split*(s: string, sep: Regex; maxsplit = -1): string =
  445. ## Splits the string ``s`` into substrings.
  446. ##
  447. ## Substrings are separated by the regular expression ``sep``
  448. ## (and the portion matched by ``sep`` is not returned).
  449. runnableExamples:
  450. import sequtils
  451. doAssert toSeq(split("00232this02939is39an22example111", re"\d+")) ==
  452. @["", "this", "is", "an", "example", ""]
  453. var last = 0
  454. var splits = maxsplit
  455. var x: int
  456. while last <= len(s):
  457. var first = last
  458. var sepLen = 1
  459. while last < len(s):
  460. x = matchLen(s, sep, last)
  461. if x >= 0:
  462. sepLen = x
  463. break
  464. inc(last)
  465. if x == 0:
  466. if last >= len(s): break
  467. inc last
  468. if splits == 0: last = len(s)
  469. yield substr(s, first, last-1)
  470. if splits == 0: break
  471. dec(splits)
  472. inc(last, sepLen)
  473. proc split*(s: string, sep: Regex, maxsplit = -1): seq[string] {.inline.} =
  474. ## Splits the string ``s`` into a seq of substrings.
  475. ##
  476. ## The portion matched by ``sep`` is not returned.
  477. result = @[]
  478. for x in split(s, sep, maxsplit): result.add x
  479. proc escapeRe*(s: string): string =
  480. ## escapes ``s`` so that it is matched verbatim when used as a regular
  481. ## expression.
  482. result = ""
  483. for c in items(s):
  484. case c
  485. of 'a'..'z', 'A'..'Z', '0'..'9', '_':
  486. result.add(c)
  487. else:
  488. result.add("\\x")
  489. result.add(toHex(ord(c), 2))