nre.nim 27 KB

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