re.nim 24 KB

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