nre.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. #
  2. # Nim's Runtime Library
  3. # (c) Copyright 2015 Nim Contributors
  4. #
  5. # See the file "copying.txt", included in this
  6. # distribution, for details about the copyright.
  7. #
  8. from pcre import nil
  9. import nre/private/util
  10. import tables
  11. from strutils import `%`
  12. from math import ceil
  13. import options
  14. from unicode import runeLenAt
  15. export options
  16. ## What is NRE?
  17. ## ============
  18. ##
  19. ## A regular expression library for Nim using PCRE to do the hard work.
  20. ##
  21. ## **Note**: If you love ``sequtils.toSeq`` we have bad news for you. This
  22. ## library doesn't work with it due to documented compiler limitations. As
  23. ## a workaround, use this:
  24. ##
  25. ## .. code-block:: nim
  26. ##
  27. ## import nre except toSeq
  28. ##
  29. ##
  30. ## Licencing
  31. ## ---------
  32. ##
  33. ## PCRE has `some additional terms`_ that you must agree to in order to use
  34. ## this module.
  35. ##
  36. ## .. _`some additional terms`: http://pcre.sourceforge.net/license.txt
  37. ##
  38. runnableExamples:
  39. let vowels = re"[aeoui]"
  40. let expectedResults = [
  41. 1 .. 1,
  42. 2 .. 2,
  43. 4 .. 4,
  44. 6 .. 6,
  45. 7 .. 7,
  46. ]
  47. var i = 0
  48. for match in "moigagoo".findIter(vowels):
  49. doAssert match.matchBounds == expectedResults[i]
  50. inc i
  51. let firstVowel = "foo".find(vowels)
  52. let hasVowel = firstVowel.isSome()
  53. if hasVowel:
  54. let matchBounds = firstVowel.get().captureBounds[-1]
  55. doAssert matchBounds.get().a == 1
  56. # Type definitions {{{
  57. type
  58. Regex* = ref object
  59. ## Represents the pattern that things are matched against, constructed with
  60. ## ``re(string)``. Examples: ``re"foo"``, ``re(r"(*ANYCRLF)(?x)foo #
  61. ## comment".``
  62. ##
  63. ## ``pattern: string``
  64. ## the string that was used to create the pattern.
  65. ##
  66. ## ``captureCount: int``
  67. ## the number of captures that the pattern has.
  68. ##
  69. ## ``captureNameId: Table[string, int]``
  70. ## a table from the capture names to their numeric id.
  71. ##
  72. ##
  73. ## Options
  74. ## .......
  75. ##
  76. ## The following options may appear anywhere in the pattern, and they affect
  77. ## the rest of it.
  78. ##
  79. ## - ``(?i)`` - case insensitive
  80. ## - ``(?m)`` - multi-line: ``^`` and ``$`` match the beginning and end of
  81. ## lines, not of the subject string
  82. ## - ``(?s)`` - ``.`` also matches newline (*dotall*)
  83. ## - ``(?U)`` - expressions are not greedy by default. ``?`` can be added
  84. ## to a qualifier to make it greedy
  85. ## - ``(?x)`` - whitespace and comments (``#``) are ignored (*extended*)
  86. ## - ``(?X)`` - character escapes without special meaning (``\w`` vs.
  87. ## ``\a``) are errors (*extra*)
  88. ##
  89. ## One or a combination of these options may appear only at the beginning
  90. ## of the pattern:
  91. ##
  92. ## - ``(*UTF8)`` - treat both the pattern and subject as UTF-8
  93. ## - ``(*UCP)`` - Unicode character properties; ``\w`` matches ``я``
  94. ## - ``(*U)`` - a combination of the two options above
  95. ## - ``(*FIRSTLINE*)`` - fails if there is not a match on the first line
  96. ## - ``(*NO_AUTO_CAPTURE)`` - turn off auto-capture for groups;
  97. ## ``(?<name>...)`` can be used to capture
  98. ## - ``(*CR)`` - newlines are separated by ``\r``
  99. ## - ``(*LF)`` - newlines are separated by ``\n`` (UNIX default)
  100. ## - ``(*CRLF)`` - newlines are separated by ``\r\n`` (Windows default)
  101. ## - ``(*ANYCRLF)`` - newlines are separated by any of the above
  102. ## - ``(*ANY)`` - newlines are separated by any of the above and Unicode
  103. ## newlines:
  104. ##
  105. ## single characters VT (vertical tab, U+000B), FF (form feed, U+000C),
  106. ## NEL (next line, U+0085), LS (line separator, U+2028), and PS
  107. ## (paragraph separator, U+2029). For the 8-bit library, the last two
  108. ## are recognized only in UTF-8 mode.
  109. ## — man pcre
  110. ##
  111. ## - ``(*JAVASCRIPT_COMPAT)`` - JavaScript compatibility
  112. ## - ``(*NO_STUDY)`` - turn off studying; study is enabled by default
  113. ##
  114. ## For more details on the leading option groups, see the `Option
  115. ## Setting <http://man7.org/linux/man-pages/man3/pcresyntax.3.html#OPTION_SETTING>`_
  116. ## and the `Newline
  117. ## Convention <http://man7.org/linux/man-pages/man3/pcresyntax.3.html#NEWLINE_CONVENTION>`_
  118. ## sections of the `PCRE syntax
  119. ## manual <http://man7.org/linux/man-pages/man3/pcresyntax.3.html>`_.
  120. pattern*: string ## not nil
  121. pcreObj: ptr pcre.Pcre ## not nil
  122. pcreExtra: ptr pcre.ExtraData ## nil
  123. captureNameToId: Table[string, int]
  124. RegexMatch* = object
  125. ## Usually seen as Option[RegexMatch], it represents the result of an
  126. ## execution. On failure, it is none, on success, it is some.
  127. ##
  128. ## ``pattern: Regex``
  129. ## the pattern that is being matched
  130. ##
  131. ## ``str: string``
  132. ## the string that was matched against
  133. ##
  134. ## ``captures[]: string``
  135. ## the string value of whatever was captured at that id. If the value
  136. ## is invalid, then behavior is undefined. If the id is ``-1``, then
  137. ## the whole match is returned. If the given capture was not matched,
  138. ## ``nil`` is returned.
  139. ##
  140. ## - ``"abc".match(re"(\w)").get.captures[0] == "a"``
  141. ## - ``"abc".match(re"(?<letter>\w)").get.captures["letter"] == "a"``
  142. ## - ``"abc".match(re"(\w)\w").get.captures[-1] == "ab"``
  143. ##
  144. ## ``captureBounds[]: Option[HSlice[int, int]]``
  145. ## gets the bounds of the given capture according to the same rules as
  146. ## the above. If the capture is not filled, then ``None`` is returned.
  147. ## The bounds are both inclusive.
  148. ##
  149. ## - ``"abc".match(re"(\w)").get.captureBounds[0].get == 0 .. 0``
  150. ## - ``"abc".match(re"").get.captureBounds[-1].get == 0 .. -1``
  151. ## - ``"abc".match(re"abc").get.captureBounds[-1].get == 0 .. 2``
  152. ##
  153. ## ``match: string``
  154. ## the full text of the match.
  155. ##
  156. ## ``matchBounds: HSlice[int, int]``
  157. ## the bounds of the match, as in ``captureBounds[]``
  158. ##
  159. ## ``(captureBounds|captures).toTable``
  160. ## returns a table with each named capture as a key.
  161. ##
  162. ## ``(captureBounds|captures).toSeq``
  163. ## returns all the captures by their number.
  164. ##
  165. ## ``$: string``
  166. ## same as ``match``
  167. pattern*: Regex ## The regex doing the matching.
  168. ## Not nil.
  169. str*: string ## The string that was matched against.
  170. ## Not nil.
  171. pcreMatchBounds: seq[HSlice[cint, cint]] ## First item is the bounds of the match
  172. ## Other items are the captures
  173. ## `a` is inclusive start, `b` is exclusive end
  174. Captures* = distinct RegexMatch
  175. CaptureBounds* = distinct RegexMatch
  176. RegexError* = ref object of Exception
  177. RegexInternalError* = ref object of RegexError
  178. ## Internal error in the module, this probably means that there is a bug
  179. InvalidUnicodeError* = ref object of RegexError
  180. ## Thrown when matching fails due to invalid unicode in strings
  181. pos*: int ## the location of the invalid unicode in bytes
  182. SyntaxError* = ref object of RegexError
  183. ## Thrown when there is a syntax error in the
  184. ## regular expression string passed in
  185. pos*: int ## the location of the syntax error in bytes
  186. pattern*: string ## the pattern that caused the problem
  187. StudyError* = ref object of RegexError
  188. ## Thrown when studying the regular expression failes
  189. ## for whatever reason. The message contains the error
  190. ## code.
  191. runnableExamples:
  192. # This MUST be kept in sync with the examples in RegexMatch
  193. doAssert "abc".match(re"(\w)").get.captures[0] == "a"
  194. doAssert "abc".match(re"(?<letter>\w)").get.captures["letter"] == "a"
  195. doAssert "abc".match(re"(\w)\w").get.captures[-1] == "ab"
  196. doAssert "abc".match(re"(\w)").get.captureBounds[0].get == 0 .. 0
  197. doAssert "abc".match(re"").get.captureBounds[-1].get == 0 .. -1
  198. doAssert "abc".match(re"abc").get.captureBounds[-1].get == 0 .. 2
  199. # }}}
  200. proc getinfo[T](pattern: Regex, opt: cint): T =
  201. let retcode = pcre.fullinfo(pattern.pcreObj, pattern.pcreExtra, opt, addr result)
  202. if retcode < 0:
  203. # XXX Error message that doesn't expose implementation details
  204. raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode])
  205. # Regex accessors {{{
  206. proc captureCount*(pattern: Regex): int =
  207. return getinfo[cint](pattern, pcre.INFO_CAPTURECOUNT)
  208. proc captureNameId*(pattern: Regex): Table[string, int] =
  209. return pattern.captureNameToId
  210. proc matchesCrLf(pattern: Regex): bool =
  211. let flags = uint32(getinfo[culong](pattern, pcre.INFO_OPTIONS))
  212. let newlineFlags = flags and (pcre.NEWLINE_CRLF or
  213. pcre.NEWLINE_ANY or
  214. pcre.NEWLINE_ANYCRLF)
  215. if newLineFlags > 0u32:
  216. return true
  217. # get flags from build config
  218. var confFlags: cint
  219. if pcre.config(pcre.CONFIG_NEWLINE, addr confFlags) != 0:
  220. assert(false, "CONFIG_NEWLINE apparently got screwed up")
  221. case confFlags
  222. of 13: return false
  223. of 10: return false
  224. of (13 shl 8) or 10: return true
  225. of -2: return true
  226. of -1: return true
  227. else: return false
  228. # }}}
  229. # Capture accessors {{{
  230. proc captureBounds*(pattern: RegexMatch): CaptureBounds = return CaptureBounds(pattern)
  231. proc captures*(pattern: RegexMatch): Captures = return Captures(pattern)
  232. proc `[]`*(pattern: CaptureBounds, i: int): Option[HSlice[int, int]] =
  233. let pattern = RegexMatch(pattern)
  234. if pattern.pcreMatchBounds[i + 1].a != -1:
  235. let bounds = pattern.pcreMatchBounds[i + 1]
  236. return some(int(bounds.a) .. int(bounds.b-1))
  237. else:
  238. return none(HSlice[int, int])
  239. proc `[]`*(pattern: Captures, i: int): string =
  240. let pattern = RegexMatch(pattern)
  241. let bounds = pattern.captureBounds[i]
  242. if bounds.isSome:
  243. let bounds = bounds.get
  244. return pattern.str.substr(bounds.a, bounds.b)
  245. else:
  246. return ""
  247. proc match*(pattern: RegexMatch): string =
  248. return pattern.captures[-1]
  249. proc matchBounds*(pattern: RegexMatch): HSlice[int, int] =
  250. return pattern.captureBounds[-1].get
  251. proc `[]`*(pattern: CaptureBounds, name: string): Option[HSlice[int, int]] =
  252. let pattern = RegexMatch(pattern)
  253. return pattern.captureBounds[pattern.pattern.captureNameToId.fget(name)]
  254. proc `[]`*(pattern: Captures, name: string): string =
  255. let pattern = RegexMatch(pattern)
  256. return pattern.captures[pattern.pattern.captureNameToId.fget(name)]
  257. template toTableImpl(cond: untyped) {.dirty.} =
  258. for key in RegexMatch(pattern).pattern.captureNameId.keys:
  259. let nextVal = pattern[key]
  260. if cond:
  261. result[key] = default
  262. else:
  263. result[key] = nextVal
  264. proc toTable*(pattern: Captures, default: string = ""): Table[string, string] =
  265. result = initTable[string, string]()
  266. toTableImpl(nextVal.len == 0)
  267. proc toTable*(pattern: CaptureBounds, default = none(HSlice[int, int])):
  268. Table[string, Option[HSlice[int, int]]] =
  269. result = initTable[string, Option[HSlice[int, int]]]()
  270. toTableImpl(nextVal.isNone)
  271. template itemsImpl(cond: untyped) {.dirty.} =
  272. for i in 0 ..< RegexMatch(pattern).pattern.captureCount:
  273. let nextVal = pattern[i]
  274. # done in this roundabout way to avoid multiple yields (potential code
  275. # bloat)
  276. let nextYieldVal = if cond: default else: nextVal
  277. yield nextYieldVal
  278. iterator items*(pattern: CaptureBounds, default = none(HSlice[int, int])): Option[HSlice[int, int]] =
  279. itemsImpl(nextVal.isNone)
  280. iterator items*(pattern: Captures, default: string = ""): string =
  281. itemsImpl(nextVal.len == 0)
  282. proc toSeq*(pattern: CaptureBounds, default = none(HSlice[int, int])): seq[Option[HSlice[int, int]]] =
  283. accumulateResult(pattern.items(default))
  284. proc toSeq*(pattern: Captures, default: string = ""): seq[string] =
  285. accumulateResult(pattern.items(default))
  286. proc `$`*(pattern: RegexMatch): string =
  287. return pattern.captures[-1]
  288. proc `==`*(a, b: Regex): bool =
  289. if not a.isNil and not b.isNil:
  290. return a.pattern == b.pattern and
  291. a.pcreObj == b.pcreObj and
  292. a.pcreExtra == b.pcreExtra
  293. else:
  294. return system.`==`(a, b)
  295. proc `==`*(a, b: RegexMatch): bool =
  296. return a.pattern == b.pattern and
  297. a.str == b.str
  298. # }}}
  299. # Creation & Destruction {{{
  300. # PCRE Options {{{
  301. const PcreOptions = {
  302. "NEVER_UTF": pcre.NEVER_UTF,
  303. "ANCHORED": pcre.ANCHORED,
  304. "DOLLAR_ENDONLY": pcre.DOLLAR_ENDONLY,
  305. "FIRSTLINE": pcre.FIRSTLINE,
  306. "NO_AUTO_CAPTURE": pcre.NO_AUTO_CAPTURE,
  307. "JAVASCRIPT_COMPAT": pcre.JAVASCRIPT_COMPAT,
  308. "U": pcre.UTF8 or pcre.UCP
  309. }.toTable
  310. # Options that are supported inside regular expressions themselves
  311. const SkipOptions = [
  312. "LIMIT_MATCH=", "LIMIT_RECURSION=", "NO_AUTO_POSSESS", "NO_START_OPT",
  313. "UTF8", "UTF16", "UTF32", "UTF", "UCP",
  314. "CR", "LF", "CRLF", "ANYCRLF", "ANY", "BSR_ANYCRLF", "BSR_UNICODE"
  315. ]
  316. proc extractOptions(pattern: string): tuple[pattern: string, flags: int, study: bool] =
  317. result = ("", 0, true)
  318. var optionStart = 0
  319. var equals = false
  320. for i, c in pattern:
  321. if optionStart == i:
  322. if c != '(':
  323. break
  324. optionStart = i
  325. elif optionStart == i-1:
  326. if c != '*':
  327. break
  328. elif c == ')':
  329. let name = pattern[optionStart+2 .. i-1]
  330. if equals or name in SkipOptions:
  331. result.pattern.add pattern[optionStart .. i]
  332. elif PcreOptions.hasKey name:
  333. result.flags = result.flags or PcreOptions[name]
  334. elif name == "NO_STUDY":
  335. result.study = false
  336. else:
  337. break
  338. optionStart = i+1
  339. equals = false
  340. elif not equals:
  341. if c == '=':
  342. equals = true
  343. if pattern[optionStart+2 .. i] notin SkipOptions:
  344. break
  345. elif c notin {'A'..'Z', '0'..'9', '_'}:
  346. break
  347. result.pattern.add pattern[optionStart .. pattern.high]
  348. # }}}
  349. proc destroyRegex(pattern: Regex) =
  350. pcre.free_substring(cast[cstring](pattern.pcreObj))
  351. pattern.pcreObj = nil
  352. if pattern.pcreExtra != nil:
  353. pcre.free_study(pattern.pcreExtra)
  354. proc getNameToNumberTable(pattern: Regex): Table[string, int] =
  355. let entryCount = getinfo[cint](pattern, pcre.INFO_NAMECOUNT)
  356. let entrySize = getinfo[cint](pattern, pcre.INFO_NAMEENTRYSIZE)
  357. let table = cast[ptr UncheckedArray[uint8]](
  358. getinfo[int](pattern, pcre.INFO_NAMETABLE))
  359. result = initTable[string, int]()
  360. for i in 0 ..< entryCount:
  361. let pos = i * entrySize
  362. let num = (int(table[pos]) shl 8) or int(table[pos + 1]) - 1
  363. var name = ""
  364. var idx = 2
  365. while table[pos + idx] != 0:
  366. name.add(char(table[pos + idx]))
  367. idx += 1
  368. result[name] = num
  369. proc initRegex(pattern: string, flags: int, study = true): Regex =
  370. new(result, destroyRegex)
  371. result.pattern = pattern
  372. var errorMsg: cstring
  373. var errOffset: cint
  374. result.pcreObj = pcre.compile(cstring(pattern),
  375. # better hope int is at least 4 bytes..
  376. cint(flags), addr errorMsg,
  377. addr errOffset, nil)
  378. if result.pcreObj == nil:
  379. # failed to compile
  380. raise SyntaxError(msg: $errorMsg, pos: errOffset, pattern: pattern)
  381. if study:
  382. var options: cint = 0
  383. var hasJit: cint
  384. if pcre.config(pcre.CONFIG_JIT, addr hasJit) == 0:
  385. if hasJit == 1'i32:
  386. options = pcre.STUDY_JIT_COMPILE
  387. result.pcreExtra = pcre.study(result.pcreObj, options, addr errorMsg)
  388. if errorMsg != nil:
  389. raise StudyError(msg: $errorMsg)
  390. result.captureNameToId = result.getNameToNumberTable()
  391. proc re*(pattern: string): Regex =
  392. let (pattern, flags, study) = extractOptions(pattern)
  393. initRegex(pattern, flags, study)
  394. # }}}
  395. # Operations {{{
  396. proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Option[RegexMatch] =
  397. var myResult = RegexMatch(pattern : pattern, str : str)
  398. # See PCRE man pages.
  399. # 2x capture count to make room for start-end pairs
  400. # 1x capture count as slack space for PCRE
  401. let vecsize = (pattern.captureCount() + 1) * 3
  402. # div 2 because each element is 2 cints long
  403. # plus 1 because we need the ceiling, not the floor
  404. myResult.pcreMatchBounds = newSeq[HSlice[cint, cint]]((vecsize + 1) div 2)
  405. myResult.pcreMatchBounds.setLen(vecsize div 3)
  406. let strlen = if endpos == int.high: str.len else: endpos+1
  407. doAssert(strlen <= str.len) # don't want buffer overflows
  408. let execRet = pcre.exec(pattern.pcreObj,
  409. pattern.pcreExtra,
  410. cstring(str),
  411. cint(strlen),
  412. cint(start),
  413. cint(flags),
  414. cast[ptr cint](addr myResult.pcreMatchBounds[0]),
  415. cint(vecsize))
  416. if execRet >= 0:
  417. return some(myResult)
  418. case execRet:
  419. of pcre.ERROR_NOMATCH:
  420. return none(RegexMatch)
  421. of pcre.ERROR_NULL:
  422. raise newException(AccessViolationError, "Expected non-null parameters")
  423. of pcre.ERROR_BADOPTION:
  424. raise RegexInternalError(msg : "Unknown pattern flag. Either a bug or " &
  425. "outdated PCRE.")
  426. of pcre.ERROR_BADUTF8, pcre.ERROR_SHORTUTF8, pcre.ERROR_BADUTF8_OFFSET:
  427. raise InvalidUnicodeError(msg : "Invalid unicode byte sequence",
  428. pos : myResult.pcreMatchBounds[0].a)
  429. else:
  430. raise RegexInternalError(msg : "Unknown internal error: " & $execRet)
  431. proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] =
  432. ## Like ```find(...)`` <#proc-find>`_, but anchored to the start of the
  433. ## string.
  434. ##
  435. runnableExamples:
  436. doAssert "foo".match(re"f").isSome
  437. doAssert "foo".match(re"o").isNone
  438. return str.matchImpl(pattern, start, endpos, pcre.ANCHORED)
  439. iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): RegexMatch =
  440. ## Works the same as ```find(...)`` <#proc-find>`_, but finds every
  441. ## non-overlapping match. ``"2222".find(re"22")`` is ``"22", "22"``, not
  442. ## ``"22", "22", "22"``.
  443. ##
  444. ## Arguments are the same as ```find(...)`` <#proc-find>`_
  445. ##
  446. ## Variants:
  447. ##
  448. ## - ``proc findAll(...)`` returns a ``seq[string]``
  449. # see pcredemo for explanation
  450. let matchesCrLf = pattern.matchesCrLf()
  451. let unicode = uint32(getinfo[culong](pattern, pcre.INFO_OPTIONS) and
  452. pcre.UTF8) > 0u32
  453. let strlen = if endpos == int.high: str.len else: endpos+1
  454. var offset = start
  455. var match: Option[RegexMatch]
  456. var neverMatched = true
  457. while true:
  458. var flags = 0
  459. if match.isSome and
  460. match.get.matchBounds.a > match.get.matchBounds.b:
  461. # 0-len match
  462. flags = pcre.NOTEMPTY_ATSTART
  463. match = str.matchImpl(pattern, offset, endpos, flags)
  464. if match.isNone:
  465. # either the end of the input or the string
  466. # cannot be split here - we also need to bail
  467. # if we've never matched and we've already tried to...
  468. if offset >= strlen or neverMatched:
  469. break
  470. if matchesCrLf and offset < (str.len - 1) and
  471. str[offset] == '\r' and str[offset + 1] == '\L':
  472. # if PCRE treats CrLf as newline, skip both at the same time
  473. offset += 2
  474. elif unicode:
  475. # XXX what about invalid unicode?
  476. offset += str.runeLenAt(offset)
  477. assert(offset <= strlen)
  478. else:
  479. offset += 1
  480. else:
  481. neverMatched = false
  482. offset = match.get.matchBounds.b + 1
  483. yield match.get
  484. proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] =
  485. ## Finds the given pattern in the string between the end and start
  486. ## positions.
  487. ##
  488. ## ``start``
  489. ## The start point at which to start matching. ``|abc`` is ``0``;
  490. ## ``a|bc`` is ``1``
  491. ##
  492. ## ``endpos``
  493. ## The maximum index for a match; ``int.high`` means the end of the
  494. ## string, otherwise it’s an inclusive upper bound.
  495. return str.matchImpl(pattern, start, endpos, 0)
  496. proc findAll*(str: string, pattern: Regex, start = 0, endpos = int.high): seq[string] =
  497. result = @[]
  498. for match in str.findIter(pattern, start, endpos):
  499. result.add(match.match)
  500. proc contains*(str: string, pattern: Regex, start = 0, endpos = int.high): bool =
  501. ## Determine if the string contains the given pattern between the end and
  502. ## start positions:
  503. ## This function is equivalent to ``isSome(str.find(pattern, start, endpos))``.
  504. ##
  505. runnableExamples:
  506. doAssert "abc".contains(re"bc") == true
  507. doAssert "abc".contains(re"cd") == false
  508. doAssert "abc".contains(re"a", start = 1) == false
  509. return isSome(str.find(pattern, start, endpos))
  510. proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] =
  511. ## Splits the string with the given regex. This works according to the
  512. ## rules that Perl and Javascript use.
  513. ##
  514. ## ``start`` behaves the same as in ```find(...)`` <#proc-find>`_.
  515. ##
  516. runnableExamples:
  517. # - If the match is zero-width, then the string is still split:
  518. doAssert "123".split(re"") == @["1", "2", "3"]
  519. # - If the pattern has a capture in it, it is added after the string
  520. # split:
  521. doAssert "12".split(re"(\d)") == @["", "1", "", "2", ""]
  522. # - If ``maxsplit != -1``, then the string will only be split
  523. # ``maxsplit - 1`` times. This means that there will be ``maxsplit``
  524. # strings in the output seq.
  525. doAssert "1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]
  526. result = @[]
  527. var lastIdx = start
  528. var splits = 0
  529. var bounds = 0 .. -1
  530. var never_ran = true
  531. for match in str.findIter(pattern, start = start):
  532. never_ran = false
  533. # bounds are inclusive:
  534. #
  535. # 0123456
  536. # ^^^
  537. # (1, 3)
  538. bounds = match.matchBounds
  539. # "12".split("") would be @["", "1", "2"], but
  540. # if we skip an empty first match, it's the correct
  541. # @["1", "2"]
  542. if bounds.a <= bounds.b or bounds.a > start:
  543. result.add(str.substr(lastIdx, bounds.a - 1))
  544. splits += 1
  545. lastIdx = bounds.b + 1
  546. for cap in match.captures:
  547. # if there are captures, include them in the result
  548. result.add(cap)
  549. if splits == maxSplit - 1:
  550. break
  551. # "12".split("\b") would be @["1", "2", ""], but
  552. # if we skip an empty last match, it's the correct
  553. # @["1", "2"]
  554. # If matches were never found, then the input string is the result
  555. if bounds.a <= bounds.b or bounds.b < str.high or never_ran:
  556. # last match: Each match takes the previous substring,
  557. # but "1 2".split(/ /) needs to return @["1", "2"].
  558. # This handles "2"
  559. result.add(str.substr(bounds.b + 1, str.high))
  560. template replaceImpl(str: string, pattern: Regex,
  561. replacement: untyped) {.dirty.} =
  562. # XXX seems very similar to split, maybe I can reduce code duplication
  563. # somehow?
  564. result = ""
  565. var lastIdx = 0
  566. for match {.inject.} in str.findIter(pattern):
  567. let bounds = match.matchBounds
  568. result.add(str.substr(lastIdx, bounds.a - 1))
  569. let nextVal = replacement
  570. result.add(nextVal)
  571. lastIdx = bounds.b + 1
  572. result.add(str.substr(lastIdx, str.len - 1))
  573. return result
  574. proc replace*(str: string, pattern: Regex,
  575. subproc: proc (match: RegexMatch): string): string =
  576. ## Replaces each match of Regex in the string with ``subproc``, which should
  577. ## never be or return ``nil``.
  578. ##
  579. ## If ``subproc`` is a ``proc (RegexMatch): string``, then it is executed with
  580. ## each match and the return value is the replacement value.
  581. ##
  582. ## If ``subproc`` is a ``proc (string): string``, then it is executed with the
  583. ## full text of the match and and the return value is the replacement
  584. ## value.
  585. ##
  586. ## If ``subproc`` is a string, the syntax is as follows:
  587. ##
  588. ## - ``$$`` - literal ``$``
  589. ## - ``$123`` - capture number ``123``
  590. ## - ``$foo`` - named capture ``foo``
  591. ## - ``${foo}`` - same as above
  592. ## - ``$1$#`` - first and second captures
  593. ## - ``$#`` - first capture
  594. ## - ``$0`` - full match
  595. ##
  596. ## If a given capture is missing, a ``ValueError`` exception is thrown.
  597. replaceImpl(str, pattern, subproc(match))
  598. proc replace*(str: string, pattern: Regex,
  599. subproc: proc (match: string): string): string =
  600. replaceImpl(str, pattern, subproc(match.match))
  601. proc replace*(str: string, pattern: Regex, sub: string): string =
  602. # - 1 because the string numbers are 0-indexed
  603. replaceImpl(str, pattern,
  604. formatStr(sub, match.captures[name], match.captures[id - 1]))
  605. # }}}
  606. let SpecialCharMatcher = re"([\\+*?[^\]$(){}=!<>|:-])"
  607. proc escapeRe*(str: string): string =
  608. ## Escapes the string so it doesn’t match any special characters.
  609. ## Incompatible with the Extra flag (``X``).
  610. str.replace(SpecialCharMatcher, "\\$1")