nre.nim 26 KB

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