nre.nim 26 KB

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