re.nim 24 KB

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