nre.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. myResult.pcreMatchBounds = newSeq[HSlice[cint, cint]](ceil(vecsize / 2).int)
  404. myResult.pcreMatchBounds.setLen(vecsize div 3)
  405. let strlen = if endpos == int.high: str.len else: endpos+1
  406. doAssert(strlen <= str.len) # don't want buffer overflows
  407. let execRet = pcre.exec(pattern.pcreObj,
  408. pattern.pcreExtra,
  409. cstring(str),
  410. cint(strlen),
  411. cint(start),
  412. cint(flags),
  413. cast[ptr cint](addr myResult.pcreMatchBounds[0]),
  414. cint(vecsize))
  415. if execRet >= 0:
  416. return some(myResult)
  417. case execRet:
  418. of pcre.ERROR_NOMATCH:
  419. return none(RegexMatch)
  420. of pcre.ERROR_NULL:
  421. raise newException(AccessViolationError, "Expected non-null parameters")
  422. of pcre.ERROR_BADOPTION:
  423. raise RegexInternalError(msg : "Unknown pattern flag. Either a bug or " &
  424. "outdated PCRE.")
  425. of pcre.ERROR_BADUTF8, pcre.ERROR_SHORTUTF8, pcre.ERROR_BADUTF8_OFFSET:
  426. raise InvalidUnicodeError(msg : "Invalid unicode byte sequence",
  427. pos : myResult.pcreMatchBounds[0].a)
  428. else:
  429. raise RegexInternalError(msg : "Unknown internal error: " & $execRet)
  430. proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] =
  431. ## Like ```find(...)`` <#proc-find>`_, but anchored to the start of the
  432. ## string.
  433. ##
  434. runnableExamples:
  435. doAssert "foo".match(re"f").isSome
  436. doAssert "foo".match(re"o").isNone
  437. return str.matchImpl(pattern, start, endpos, pcre.ANCHORED)
  438. iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): RegexMatch =
  439. ## Works the same as ```find(...)`` <#proc-find>`_, but finds every
  440. ## non-overlapping match. ``"2222".find(re"22")`` is ``"22", "22"``, not
  441. ## ``"22", "22", "22"``.
  442. ##
  443. ## Arguments are the same as ```find(...)`` <#proc-find>`_
  444. ##
  445. ## Variants:
  446. ##
  447. ## - ``proc findAll(...)`` returns a ``seq[string]``
  448. # see pcredemo for explanation
  449. let matchesCrLf = pattern.matchesCrLf()
  450. let unicode = uint32(getinfo[culong](pattern, pcre.INFO_OPTIONS) and
  451. pcre.UTF8) > 0u32
  452. let strlen = if endpos == int.high: str.len else: endpos+1
  453. var offset = start
  454. var match: Option[RegexMatch]
  455. var neverMatched = true
  456. while true:
  457. var flags = 0
  458. if match.isSome and
  459. match.get.matchBounds.a > match.get.matchBounds.b:
  460. # 0-len match
  461. flags = pcre.NOTEMPTY_ATSTART
  462. match = str.matchImpl(pattern, offset, endpos, flags)
  463. if match.isNone:
  464. # either the end of the input or the string
  465. # cannot be split here - we also need to bail
  466. # if we've never matched and we've already tried to...
  467. if offset >= strlen or neverMatched:
  468. break
  469. if matchesCrLf and offset < (str.len - 1) and
  470. str[offset] == '\r' and str[offset + 1] == '\L':
  471. # if PCRE treats CrLf as newline, skip both at the same time
  472. offset += 2
  473. elif unicode:
  474. # XXX what about invalid unicode?
  475. offset += str.runeLenAt(offset)
  476. assert(offset <= strlen)
  477. else:
  478. offset += 1
  479. else:
  480. neverMatched = false
  481. offset = match.get.matchBounds.b + 1
  482. yield match.get
  483. proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] =
  484. ## Finds the given pattern in the string between the end and start
  485. ## positions.
  486. ##
  487. ## ``start``
  488. ## The start point at which to start matching. ``|abc`` is ``0``;
  489. ## ``a|bc`` is ``1``
  490. ##
  491. ## ``endpos``
  492. ## The maximum index for a match; ``int.high`` means the end of the
  493. ## string, otherwise it’s an inclusive upper bound.
  494. return str.matchImpl(pattern, start, endpos, 0)
  495. proc findAll*(str: string, pattern: Regex, start = 0, endpos = int.high): seq[string] =
  496. result = @[]
  497. for match in str.findIter(pattern, start, endpos):
  498. result.add(match.match)
  499. proc contains*(str: string, pattern: Regex, start = 0, endpos = int.high): bool =
  500. ## Determine if the string contains the given pattern between the end and
  501. ## start positions:
  502. ## This function is equivalent to ``isSome(str.find(pattern, start, endpos))``.
  503. ##
  504. runnableExamples:
  505. doAssert "abc".contains(re"bc") == true
  506. doAssert "abc".contains(re"cd") == false
  507. doAssert "abc".contains(re"a", start = 1) == false
  508. return isSome(str.find(pattern, start, endpos))
  509. proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] =
  510. ## Splits the string with the given regex. This works according to the
  511. ## rules that Perl and Javascript use.
  512. ##
  513. ## ``start`` behaves the same as in ```find(...)`` <#proc-find>`_.
  514. ##
  515. runnableExamples:
  516. # - If the match is zero-width, then the string is still split:
  517. doAssert "123".split(re"") == @["1", "2", "3"]
  518. # - If the pattern has a capture in it, it is added after the string
  519. # split:
  520. doAssert "12".split(re"(\d)") == @["", "1", "", "2", ""]
  521. # - If ``maxsplit != -1``, then the string will only be split
  522. # ``maxsplit - 1`` times. This means that there will be ``maxsplit``
  523. # strings in the output seq.
  524. doAssert "1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]
  525. result = @[]
  526. var lastIdx = start
  527. var splits = 0
  528. var bounds = 0 .. -1
  529. var never_ran = true
  530. for match in str.findIter(pattern, start = start):
  531. never_ran = false
  532. # bounds are inclusive:
  533. #
  534. # 0123456
  535. # ^^^
  536. # (1, 3)
  537. bounds = match.matchBounds
  538. # "12".split("") would be @["", "1", "2"], but
  539. # if we skip an empty first match, it's the correct
  540. # @["1", "2"]
  541. if bounds.a <= bounds.b or bounds.a > start:
  542. result.add(str.substr(lastIdx, bounds.a - 1))
  543. splits += 1
  544. lastIdx = bounds.b + 1
  545. for cap in match.captures:
  546. # if there are captures, include them in the result
  547. result.add(cap)
  548. if splits == maxSplit - 1:
  549. break
  550. # "12".split("\b") would be @["1", "2", ""], but
  551. # if we skip an empty last match, it's the correct
  552. # @["1", "2"]
  553. # If matches were never found, then the input string is the result
  554. if bounds.a <= bounds.b or bounds.b < str.high or never_ran:
  555. # last match: Each match takes the previous substring,
  556. # but "1 2".split(/ /) needs to return @["1", "2"].
  557. # This handles "2"
  558. result.add(str.substr(bounds.b + 1, str.high))
  559. template replaceImpl(str: string, pattern: Regex,
  560. replacement: untyped) {.dirty.} =
  561. # XXX seems very similar to split, maybe I can reduce code duplication
  562. # somehow?
  563. result = ""
  564. var lastIdx = 0
  565. for match {.inject.} in str.findIter(pattern):
  566. let bounds = match.matchBounds
  567. result.add(str.substr(lastIdx, bounds.a - 1))
  568. let nextVal = replacement
  569. result.add(nextVal)
  570. lastIdx = bounds.b + 1
  571. result.add(str.substr(lastIdx, str.len - 1))
  572. return result
  573. proc replace*(str: string, pattern: Regex,
  574. subproc: proc (match: RegexMatch): string): string =
  575. ## Replaces each match of Regex in the string with ``subproc``, which should
  576. ## never be or return ``nil``.
  577. ##
  578. ## If ``subproc`` is a ``proc (RegexMatch): string``, then it is executed with
  579. ## each match and the return value is the replacement value.
  580. ##
  581. ## If ``subproc`` is a ``proc (string): string``, then it is executed with the
  582. ## full text of the match and and the return value is the replacement
  583. ## value.
  584. ##
  585. ## If ``subproc`` is a string, the syntax is as follows:
  586. ##
  587. ## - ``$$`` - literal ``$``
  588. ## - ``$123`` - capture number ``123``
  589. ## - ``$foo`` - named capture ``foo``
  590. ## - ``${foo}`` - same as above
  591. ## - ``$1$#`` - first and second captures
  592. ## - ``$#`` - first capture
  593. ## - ``$0`` - full match
  594. ##
  595. ## If a given capture is missing, a ``ValueError`` exception is thrown.
  596. replaceImpl(str, pattern, subproc(match))
  597. proc replace*(str: string, pattern: Regex,
  598. subproc: proc (match: string): string): string =
  599. replaceImpl(str, pattern, subproc(match.match))
  600. proc replace*(str: string, pattern: Regex, sub: string): string =
  601. # - 1 because the string numbers are 0-indexed
  602. replaceImpl(str, pattern,
  603. formatStr(sub, match.captures[name], match.captures[id - 1]))
  604. # }}}
  605. let SpecialCharMatcher = re"([\\+*?[^\]$(){}=!<>|:-])"
  606. proc escapeRe*(str: string): string =
  607. ## Escapes the string so it doesn’t match any special characters.
  608. ## Incompatible with the Extra flag (``X``).
  609. str.replace(SpecialCharMatcher, "\\$1")