re.nim 24 KB

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