re.nim 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. const MaxReBufSize* = high(cint)
  127. ## Maximum PCRE (API 1) buffer start/size equal to `high(cint)`, which even
  128. ## for 64-bit systems can be either 2`31`:sup:-1 or 2`63`:sup:-1.
  129. proc findBounds*(buf: cstring, pattern: Regex, matches: var openArray[string],
  130. start = 0, bufSize: int): tuple[first, last: int] =
  131. ## returns the starting position and end position of `pattern` in `buf`
  132. ## (where `buf` has length `bufSize` and is not necessarily `'\0'` terminated),
  133. ## and the captured
  134. ## substrings in the array `matches`. If it does not match, nothing
  135. ## is written into `matches` and `(-1,0)` is returned.
  136. var
  137. rtarray = initRtArray[cint]((matches.len+1)*3)
  138. rawMatches = rtarray.getRawData
  139. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  140. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  141. if res < 0'i32: return (-1, 0)
  142. for i in 1..int(res)-1:
  143. var a = rawMatches[i * 2]
  144. var b = rawMatches[i * 2 + 1]
  145. if a >= 0'i32: matches[i-1] = bufSubstr(buf, int(a), int(b))
  146. else: matches[i-1] = ""
  147. return (rawMatches[0].int, rawMatches[1].int - 1)
  148. proc findBounds*(s: string, pattern: Regex, matches: var openArray[string],
  149. start = 0): tuple[first, last: int] {.inline.} =
  150. ## returns the starting position and end position of `pattern` in `s`
  151. ## and the captured substrings in the array `matches`.
  152. ## If it does not match, nothing
  153. ## is written into `matches` and `(-1,0)` is returned.
  154. result = findBounds(cstring(s), pattern, matches,
  155. min(start, MaxReBufSize), min(s.len, MaxReBufSize))
  156. proc findBounds*(buf: cstring, pattern: Regex,
  157. matches: var openArray[tuple[first, last: int]],
  158. start = 0, bufSize: int): tuple[first, last: int] =
  159. ## returns the starting position and end position of `pattern` in `buf`
  160. ## (where `buf` has length `bufSize` and is not necessarily `'\0'` terminated),
  161. ## and the captured substrings in the array `matches`.
  162. ## If it does not match, nothing is written into `matches` and
  163. ## `(-1,0)` is returned.
  164. var
  165. rtarray = initRtArray[cint]((matches.len+1)*3)
  166. rawMatches = rtarray.getRawData
  167. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  168. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  169. if res < 0'i32: return (-1, 0)
  170. for i in 1..int(res)-1:
  171. var a = rawMatches[i * 2]
  172. var b = rawMatches[i * 2 + 1]
  173. if a >= 0'i32: matches[i-1] = (int(a), int(b)-1)
  174. else: matches[i-1] = (-1,0)
  175. return (rawMatches[0].int, rawMatches[1].int - 1)
  176. proc findBounds*(s: string, pattern: Regex,
  177. matches: var openArray[tuple[first, last: int]],
  178. start = 0): tuple[first, last: int] {.inline.} =
  179. ## returns the starting position and end position of `pattern` in `s`
  180. ## and the captured substrings in the array `matches`.
  181. ## If it does not match, nothing is written into `matches` and
  182. ## `(-1,0)` is returned.
  183. result = findBounds(cstring(s), pattern, matches,
  184. min(start, MaxReBufSize), min(s.len, MaxReBufSize))
  185. proc findBoundsImpl(buf: cstring, pattern: Regex,
  186. start = 0, bufSize = 0, flags = 0): tuple[first, last: int] =
  187. var rtarray = initRtArray[cint](3)
  188. let rawMatches = rtarray.getRawData
  189. let res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, flags.int32,
  190. cast[ptr cint](rawMatches), 3)
  191. if res < 0'i32:
  192. result = (-1, 0)
  193. else:
  194. result = (int(rawMatches[0]), int(rawMatches[1]-1))
  195. proc findBounds*(buf: cstring, pattern: Regex,
  196. start = 0, bufSize: int): tuple[first, last: int] =
  197. ## returns the `first` and `last` position of `pattern` in `buf`,
  198. ## where `buf` has length `bufSize` (not necessarily `'\0'` terminated).
  199. ## If it does not match, `(-1,0)` is returned.
  200. var
  201. rtarray = initRtArray[cint](3)
  202. rawMatches = rtarray.getRawData
  203. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  204. cast[ptr cint](rawMatches), 3)
  205. if res < 0'i32: return (int(res), 0)
  206. return (int(rawMatches[0]), int(rawMatches[1]-1))
  207. proc findBounds*(s: string, pattern: Regex,
  208. start = 0): tuple[first, last: int] {.inline.} =
  209. ## returns the `first` and `last` position of `pattern` in `s`.
  210. ## If it does not match, `(-1,0)` is returned.
  211. ##
  212. ## Note: there is a speed improvement if the matches do not need to be captured.
  213. runnableExamples:
  214. assert findBounds("01234abc89", re"abc") == (5,7)
  215. result = findBounds(cstring(s), pattern,
  216. min(start, MaxReBufSize), min(s.len, MaxReBufSize))
  217. proc matchOrFind(buf: cstring, pattern: Regex, start, bufSize: int, flags: cint): cint =
  218. var
  219. rtarray = initRtArray[cint](3)
  220. rawMatches = rtarray.getRawData
  221. result = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, flags,
  222. cast[ptr cint](rawMatches), 3)
  223. if result >= 0'i32:
  224. result = rawMatches[1] - rawMatches[0]
  225. proc matchLen*(s: string, pattern: Regex, matches: var openArray[string],
  226. start = 0): int {.inline.} =
  227. ## the same as `match`, but it returns the length of the match,
  228. ## if there is no match, `-1` is returned. Note that a match length
  229. ## of zero can happen.
  230. result = matchOrFind(cstring(s), pattern, matches, start.cint, s.len.cint, pcre.ANCHORED)
  231. proc matchLen*(buf: cstring, pattern: Regex, matches: var openArray[string],
  232. start = 0, bufSize: int): int {.inline.} =
  233. ## the same as `match`, but it returns the length of the match,
  234. ## if there is no match, `-1` is returned. Note that a match length
  235. ## of zero can happen.
  236. return matchOrFind(buf, pattern, matches, start.cint, bufSize.cint, pcre.ANCHORED)
  237. proc matchLen*(s: string, pattern: Regex, start = 0): int {.inline.} =
  238. ## the same as `match`, but it returns the length of the match,
  239. ## if there is no match, `-1` is returned. Note that a match length
  240. ## of zero can happen.
  241. ##
  242. runnableExamples:
  243. doAssert matchLen("abcdefg", re"cde", 2) == 3
  244. doAssert matchLen("abcdefg", re"abcde") == 5
  245. doAssert matchLen("abcdefg", re"cde") == -1
  246. result = matchOrFind(cstring(s), pattern, start.cint, s.len.cint, pcre.ANCHORED)
  247. proc matchLen*(buf: cstring, pattern: Regex, start = 0, bufSize: int): int {.inline.} =
  248. ## the same as `match`, but it returns the length of the match,
  249. ## if there is no match, `-1` is returned. Note that a match length
  250. ## of zero can happen.
  251. result = matchOrFind(buf, pattern, start.cint, bufSize, pcre.ANCHORED)
  252. proc match*(s: string, pattern: Regex, start = 0): bool {.inline.} =
  253. ## returns `true` if `s[start..]` matches the `pattern`.
  254. result = matchLen(cstring(s), pattern, start, s.len) != -1
  255. proc match*(s: string, pattern: Regex, matches: var openArray[string],
  256. start = 0): bool {.inline.} =
  257. ## returns `true` if `s[start..]` matches the `pattern` and
  258. ## the captured substrings in the array `matches`. If it does not
  259. ## match, nothing is written into `matches` and `false` is
  260. ## returned.
  261. ##
  262. runnableExamples:
  263. import std/sequtils
  264. var matches: array[2, string]
  265. if match("abcdefg", re"c(d)ef(g)", matches, 2):
  266. doAssert toSeq(matches) == @["d", "g"]
  267. result = matchLen(cstring(s), pattern, matches, start, s.len) != -1
  268. proc match*(buf: cstring, pattern: Regex, matches: var openArray[string],
  269. start = 0, bufSize: int): bool {.inline.} =
  270. ## returns `true` if `buf[start..<bufSize]` matches the `pattern` and
  271. ## the captured substrings in the array `matches`. If it does not
  272. ## match, nothing is written into `matches` and `false` is
  273. ## returned.
  274. ## `buf` has length `bufSize` (not necessarily `'\0'` terminated).
  275. result = matchLen(buf, pattern, matches, start, bufSize) != -1
  276. proc find*(buf: cstring, pattern: Regex, matches: var openArray[string],
  277. start = 0, bufSize: int): int =
  278. ## returns the starting position of `pattern` in `buf` and the captured
  279. ## substrings in the array `matches`. If it does not match, nothing
  280. ## is written into `matches` and `-1` is returned.
  281. ## `buf` has length `bufSize` (not necessarily `'\0'` terminated).
  282. var
  283. rtarray = initRtArray[cint]((matches.len+1)*3)
  284. rawMatches = rtarray.getRawData
  285. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  286. cast[ptr cint](rawMatches), (matches.len+1).cint*3)
  287. if res < 0'i32: return res
  288. for i in 1..int(res)-1:
  289. var a = rawMatches[i * 2]
  290. var b = rawMatches[i * 2 + 1]
  291. if a >= 0'i32: matches[i-1] = bufSubstr(buf, int(a), int(b))
  292. else: matches[i-1] = ""
  293. return rawMatches[0]
  294. proc find*(s: string, pattern: Regex, matches: var openArray[string],
  295. start = 0): int {.inline.} =
  296. ## returns the starting position of `pattern` in `s` and the captured
  297. ## substrings in the array `matches`. If it does not match, nothing
  298. ## is written into `matches` and `-1` is returned.
  299. result = find(cstring(s), pattern, matches, start, s.len)
  300. proc find*(buf: cstring, pattern: Regex, start = 0, bufSize: int): int =
  301. ## returns the starting position of `pattern` in `buf`,
  302. ## where `buf` has length `bufSize` (not necessarily `'\0'` terminated).
  303. ## If it does not match, `-1` is returned.
  304. var
  305. rtarray = initRtArray[cint](3)
  306. rawMatches = rtarray.getRawData
  307. res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, start.cint, 0'i32,
  308. cast[ptr cint](rawMatches), 3)
  309. if res < 0'i32: return res
  310. return rawMatches[0]
  311. proc find*(s: string, pattern: Regex, start = 0): int {.inline.} =
  312. ## returns the starting position of `pattern` in `s`. If it does not
  313. ## match, `-1` is returned. We start the scan at `start`.
  314. runnableExamples:
  315. doAssert find("abcdefg", re"cde") == 2
  316. doAssert find("abcdefg", re"abc") == 0
  317. doAssert find("abcdefg", re"zz") == -1 # not found
  318. doAssert find("abcdefg", re"cde", start = 2) == 2 # still 2
  319. doAssert find("abcdefg", re"cde", start = 3) == -1 # we're past the start position
  320. doAssert find("xabc", re"(?<=x|y)abc", start = 1) == 1
  321. # lookbehind assertion `(?<=x|y)` can look behind `start`
  322. result = find(cstring(s), pattern, start, s.len)
  323. iterator findAll*(s: string, pattern: Regex, start = 0): string =
  324. ## Yields all matching *substrings* of `s` that match `pattern`.
  325. ##
  326. ## Note that since this is an iterator you should not modify the string you
  327. ## are iterating over: bad things could happen.
  328. var
  329. i = int32(start)
  330. rtarray = initRtArray[cint](3)
  331. rawMatches = rtarray.getRawData
  332. while true:
  333. let res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, i, 0'i32,
  334. cast[ptr cint](rawMatches), 3)
  335. if res < 0'i32: break
  336. let a = rawMatches[0]
  337. let b = rawMatches[1]
  338. if a == b and a == i: break
  339. yield substr(s, int(a), int(b)-1)
  340. i = b
  341. iterator findAll*(buf: cstring, pattern: Regex, start = 0, bufSize: int): string =
  342. ## Yields all matching `substrings` of `s` that match `pattern`.
  343. ##
  344. ## Note that since this is an iterator you should not modify the string you
  345. ## are iterating over: bad things could happen.
  346. var
  347. i = int32(start)
  348. rtarray = initRtArray[cint](3)
  349. rawMatches = rtarray.getRawData
  350. while true:
  351. let res = pcre.exec(pattern.h, pattern.e, buf, bufSize.cint, i, 0'i32,
  352. cast[ptr cint](rawMatches), 3)
  353. if res < 0'i32: break
  354. let a = rawMatches[0]
  355. let b = rawMatches[1]
  356. if a == b and a == i: break
  357. var str = newString(b-a)
  358. copyMem(str[0].addr, unsafeAddr(buf[a]), b-a)
  359. yield str
  360. i = b
  361. proc findAll*(s: string, pattern: Regex, start = 0): seq[string] {.inline.} =
  362. ## returns all matching `substrings` of `s` that match `pattern`.
  363. ## If it does not match, @[] is returned.
  364. result = @[]
  365. for x in findAll(s, pattern, start): result.add x
  366. template `=~` *(s: string, pattern: Regex): untyped =
  367. ## This calls `match` with an implicit declared `matches` array that
  368. ## can be used in the scope of the `=~` call:
  369. runnableExamples:
  370. proc parse(line: string): string =
  371. if line =~ re"\s*(\w+)\s*\=\s*(\w+)": # matches a key=value pair:
  372. result = $(matches[0], matches[1])
  373. elif line =~ re"\s*(\#.*)": # matches a comment
  374. # note that the implicit `matches` array is different from 1st branch
  375. result = $(matches[0],)
  376. else: doAssert false
  377. doAssert not declared(matches)
  378. doAssert parse("NAME = LENA") == """("NAME", "LENA")"""
  379. doAssert parse(" # comment ... ") == """("# comment ... ",)"""
  380. bind MaxSubpatterns
  381. when not declaredInScope(matches):
  382. var matches {.inject.}: array[MaxSubpatterns, string]
  383. match(s, pattern, matches)
  384. # ------------------------- more string handling ------------------------------
  385. proc contains*(s: string, pattern: Regex, start = 0): bool {.inline.} =
  386. ## same as `find(s, pattern, start) >= 0`
  387. return find(s, pattern, start) >= 0
  388. proc contains*(s: string, pattern: Regex, matches: var openArray[string],
  389. start = 0): bool {.inline.} =
  390. ## same as `find(s, pattern, matches, start) >= 0`
  391. return find(s, pattern, matches, start) >= 0
  392. proc startsWith*(s: string, prefix: Regex): bool {.inline.} =
  393. ## returns true if `s` starts with the pattern `prefix`
  394. result = matchLen(s, prefix) >= 0
  395. proc endsWith*(s: string, suffix: Regex): bool {.inline.} =
  396. ## returns true if `s` ends with the pattern `suffix`
  397. for i in 0 .. s.len-1:
  398. if matchLen(s, suffix, i) == s.len - i: return true
  399. proc replace*(s: string, sub: Regex, by = ""): string =
  400. ## Replaces `sub` in `s` by the string `by`. Captures cannot be
  401. ## accessed in `by`.
  402. runnableExamples:
  403. doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)") == "; "
  404. doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)", "?") == "?; ?"
  405. result = ""
  406. var prev = 0
  407. var flags = int32(0)
  408. while prev < s.len:
  409. var match = findBoundsImpl(s.cstring, sub, prev, s.len, flags)
  410. flags = 0
  411. if match.first < 0: break
  412. add(result, substr(s, prev, match.first-1))
  413. add(result, by)
  414. if match.first > match.last:
  415. # 0-len match
  416. flags = pcre.NOTEMPTY_ATSTART
  417. prev = match.last + 1
  418. add(result, substr(s, prev))
  419. proc replacef*(s: string, sub: Regex, by: string): string =
  420. ## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by`
  421. ## with the notation `$i` and `$#` (see strutils.\`%\`).
  422. runnableExamples:
  423. doAssert "var1=key; var2=key2".replacef(re"(\w+)=(\w+)", "$1<-$2$2") ==
  424. "var1<-keykey; var2<-key2key2"
  425. result = ""
  426. var caps: array[MaxSubpatterns, string]
  427. var prev = 0
  428. while prev < s.len:
  429. var match = findBounds(s, sub, caps, prev)
  430. if match.first < 0: break
  431. add(result, substr(s, prev, match.first-1))
  432. addf(result, by, caps)
  433. if match.last + 1 == prev: break
  434. prev = match.last + 1
  435. add(result, substr(s, prev))
  436. proc multiReplace*(s: string, subs: openArray[
  437. tuple[pattern: Regex, repl: string]]): string =
  438. ## Returns a modified copy of `s` with the substitutions in `subs`
  439. ## applied in parallel.
  440. result = ""
  441. var i = 0
  442. var caps: array[MaxSubpatterns, string]
  443. while i < s.len:
  444. block searchSubs:
  445. for j in 0..high(subs):
  446. var x = matchLen(s, subs[j][0], caps, i)
  447. if x > 0:
  448. addf(result, subs[j][1], caps)
  449. inc(i, x)
  450. break searchSubs
  451. add(result, s[i])
  452. inc(i)
  453. # copy the rest:
  454. add(result, substr(s, i))
  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)
  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. runnableExamples:
  468. import std/sequtils
  469. doAssert toSeq(split("00232this02939is39an22example111", re"\d+")) ==
  470. @["", "this", "is", "an", "example", ""]
  471. var last = 0
  472. var splits = maxsplit
  473. var x: int
  474. while last <= len(s):
  475. var first = last
  476. var sepLen = 1
  477. while last < len(s):
  478. x = matchLen(s, sep, last)
  479. if x >= 0:
  480. sepLen = x
  481. break
  482. inc(last)
  483. if x == 0:
  484. if last >= len(s): break
  485. inc last
  486. if splits == 0: last = len(s)
  487. yield substr(s, first, last-1)
  488. if splits == 0: break
  489. dec(splits)
  490. inc(last, sepLen)
  491. proc split*(s: string, sep: Regex, maxsplit = -1): seq[string] {.inline.} =
  492. ## Splits the string `s` into a seq of substrings.
  493. ##
  494. ## The portion matched by `sep` is not returned.
  495. result = @[]
  496. for x in split(s, sep, maxsplit): result.add x
  497. proc escapeRe*(s: string): string =
  498. ## escapes `s` so that it is matched verbatim when used as a regular
  499. ## expression.
  500. result = ""
  501. for c in items(s):
  502. case c
  503. of 'a'..'z', 'A'..'Z', '0'..'9', '_':
  504. result.add(c)
  505. else:
  506. result.add("\\x")
  507. result.add(toHex(ord(c), 2))