nre.nim 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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 pcre import nil
  60. import nre/private/util
  61. import tables
  62. from strutils import `%`
  63. import options
  64. from 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. pcre.free_substring(cast[cstring](pattern.pcreObj))
  204. if pattern.pcreExtra != nil:
  205. pcre.free_study(pattern.pcreExtra)
  206. proc getinfo[T](pattern: Regex, opt: cint): T =
  207. let retcode = pcre.fullinfo(pattern.pcreObj, pattern.pcreExtra, opt, addr result)
  208. if retcode < 0:
  209. # XXX Error message that doesn't expose implementation details
  210. raise newException(FieldDefect, "Invalid getinfo for $1, errno $2" % [$opt, $retcode])
  211. proc getNameToNumberTable(pattern: Regex): Table[string, int] =
  212. let entryCount = getinfo[cint](pattern, pcre.INFO_NAMECOUNT)
  213. let entrySize = getinfo[cint](pattern, pcre.INFO_NAMEENTRYSIZE)
  214. let table = cast[ptr UncheckedArray[uint8]](
  215. getinfo[int](pattern, pcre.INFO_NAMETABLE))
  216. result = initTable[string, int]()
  217. for i in 0 ..< entryCount:
  218. let pos = i * entrySize
  219. let num = (int(table[pos]) shl 8) or int(table[pos + 1]) - 1
  220. var name = ""
  221. var idx = 2
  222. while table[pos + idx] != 0:
  223. name.add(char(table[pos + idx]))
  224. idx += 1
  225. result[name] = num
  226. proc initRegex(pattern: string, flags: int, study = true): Regex =
  227. new(result, destroyRegex)
  228. result.pattern = pattern
  229. var errorMsg: cstring
  230. var errOffset: cint
  231. result.pcreObj = pcre.compile(cstring(pattern),
  232. # better hope int is at least 4 bytes..
  233. cint(flags), addr errorMsg,
  234. addr errOffset, nil)
  235. if result.pcreObj == nil:
  236. # failed to compile
  237. raise SyntaxError(msg: $errorMsg, pos: errOffset, pattern: pattern)
  238. if study:
  239. var options: cint = 0
  240. var hasJit: cint
  241. if pcre.config(pcre.CONFIG_JIT, addr hasJit) == 0:
  242. if hasJit == 1'i32:
  243. options = pcre.STUDY_JIT_COMPILE
  244. result.pcreExtra = pcre.study(result.pcreObj, options, addr errorMsg)
  245. if errorMsg != nil:
  246. raise StudyError(msg: $errorMsg)
  247. result.captureNameToId = result.getNameToNumberTable()
  248. proc captureCount*(pattern: Regex): int =
  249. return getinfo[cint](pattern, pcre.INFO_CAPTURECOUNT)
  250. proc captureNameId*(pattern: Regex): Table[string, int] =
  251. return pattern.captureNameToId
  252. proc matchesCrLf(pattern: Regex): bool =
  253. let flags = uint32(getinfo[culong](pattern, pcre.INFO_OPTIONS))
  254. let newlineFlags = flags and (pcre.NEWLINE_CRLF or
  255. pcre.NEWLINE_ANY or
  256. pcre.NEWLINE_ANYCRLF)
  257. if newlineFlags > 0u32:
  258. return true
  259. # get flags from build config
  260. var confFlags: cint
  261. if pcre.config(pcre.CONFIG_NEWLINE, addr confFlags) != 0:
  262. assert(false, "CONFIG_NEWLINE apparently got screwed up")
  263. case confFlags
  264. of 13: return false
  265. of 10: return false
  266. of (13 shl 8) or 10: return true
  267. of -2: return true
  268. of -1: return true
  269. else: return false
  270. func captureBounds*(pattern: RegexMatch): CaptureBounds = return CaptureBounds(pattern)
  271. func captures*(pattern: RegexMatch): Captures = return Captures(pattern)
  272. func contains*(pattern: CaptureBounds, i: int): bool =
  273. let pattern = RegexMatch(pattern)
  274. pattern.pcreMatchBounds[i + 1].a != -1
  275. func contains*(pattern: Captures, i: int): bool =
  276. i in CaptureBounds(pattern)
  277. func `[]`*(pattern: CaptureBounds, i: int): HSlice[int, int] =
  278. let pattern = RegexMatch(pattern)
  279. if not (i in pattern.captureBounds):
  280. raise newException(IndexDefect, "Group '" & $i & "' was not captured")
  281. let bounds = pattern.pcreMatchBounds[i + 1]
  282. int(bounds.a)..int(bounds.b-1)
  283. func `[]`*(pattern: Captures, i: int): string =
  284. let pattern = RegexMatch(pattern)
  285. let bounds = pattern.captureBounds[i]
  286. pattern.str.substr(bounds.a, bounds.b)
  287. func match*(pattern: RegexMatch): string =
  288. return pattern.captures[-1]
  289. func matchBounds*(pattern: RegexMatch): HSlice[int, int] =
  290. return pattern.captureBounds[-1]
  291. func contains*(pattern: CaptureBounds, name: string): bool =
  292. let pattern = RegexMatch(pattern)
  293. let nameToId = pattern.pattern.captureNameToId
  294. if not (name in nameToId):
  295. return false
  296. nameToId[name] in pattern.captureBounds
  297. func contains*(pattern: Captures, name: string): bool =
  298. name in CaptureBounds(pattern)
  299. func checkNamedCaptured(pattern: RegexMatch, name: string) =
  300. if not (name in pattern.captureBounds):
  301. raise newException(KeyError, "Group '" & name & "' was not captured")
  302. func `[]`*(pattern: CaptureBounds, name: string): HSlice[int, int] =
  303. let pattern = RegexMatch(pattern)
  304. checkNamedCaptured(pattern, name)
  305. {.noSideEffect.}:
  306. result = pattern.captureBounds[pattern.pattern.captureNameToId[name]]
  307. func `[]`*(pattern: Captures, name: string): string =
  308. let pattern = RegexMatch(pattern)
  309. checkNamedCaptured(pattern, name)
  310. {.noSideEffect.}:
  311. result = pattern.captures[pattern.pattern.captureNameToId[name]]
  312. template toTableImpl() {.dirty.} =
  313. for key in RegexMatch(pattern).pattern.captureNameId.keys:
  314. if key in pattern:
  315. result[key] = pattern[key]
  316. func toTable*(pattern: Captures): Table[string, string] =
  317. result = initTable[string, string]()
  318. toTableImpl()
  319. func toTable*(pattern: CaptureBounds): Table[string, HSlice[int, int]] =
  320. result = initTable[string, HSlice[int, int]]()
  321. toTableImpl()
  322. template itemsImpl() {.dirty.} =
  323. for i in 0 ..< RegexMatch(pattern).pattern.captureCount:
  324. # done in this roundabout way to avoid multiple yields (potential code
  325. # bloat)
  326. let nextYieldVal = if i in pattern:
  327. some(pattern[i])
  328. else:
  329. default
  330. yield nextYieldVal
  331. iterator items*(pattern: CaptureBounds,
  332. default = none(HSlice[int, int])): Option[HSlice[int, int]] =
  333. itemsImpl()
  334. iterator items*(pattern: Captures,
  335. default: Option[string] = none(string)): Option[string] =
  336. itemsImpl()
  337. proc toSeq*(pattern: CaptureBounds,
  338. default = none(HSlice[int, int])): seq[Option[HSlice[int, int]]] =
  339. result = @[]
  340. for it in pattern.items(default): result.add it
  341. proc toSeq*(pattern: Captures,
  342. default: Option[string] = none(string)): seq[Option[string]] =
  343. result = @[]
  344. for it in pattern.items(default): result.add it
  345. proc `$`*(pattern: RegexMatch): string =
  346. return pattern.captures[-1]
  347. proc `==`*(a, b: Regex): bool =
  348. if not a.isNil and not b.isNil:
  349. return a.pattern == b.pattern and
  350. a.pcreObj == b.pcreObj and
  351. a.pcreExtra == b.pcreExtra
  352. else:
  353. return system.`==`(a, b)
  354. proc `==`*(a, b: RegexMatch): bool =
  355. return a.pattern == b.pattern and
  356. a.str == b.str
  357. const PcreOptions = {
  358. "NEVER_UTF": pcre.NEVER_UTF,
  359. "ANCHORED": pcre.ANCHORED,
  360. "DOLLAR_ENDONLY": pcre.DOLLAR_ENDONLY,
  361. "FIRSTLINE": pcre.FIRSTLINE,
  362. "NO_AUTO_CAPTURE": pcre.NO_AUTO_CAPTURE,
  363. "JAVASCRIPT_COMPAT": pcre.JAVASCRIPT_COMPAT,
  364. "U": pcre.UTF8 or pcre.UCP
  365. }.toTable
  366. # Options that are supported inside regular expressions themselves
  367. const SkipOptions = [
  368. "LIMIT_MATCH=", "LIMIT_RECURSION=", "NO_AUTO_POSSESS", "NO_START_OPT",
  369. "UTF8", "UTF16", "UTF32", "UTF", "UCP",
  370. "CR", "LF", "CRLF", "ANYCRLF", "ANY", "BSR_ANYCRLF", "BSR_UNICODE"
  371. ]
  372. proc extractOptions(pattern: string): tuple[pattern: string, flags: int, study: bool] =
  373. result = ("", 0, true)
  374. var optionStart = 0
  375. var equals = false
  376. for i, c in pattern:
  377. if optionStart == i:
  378. if c != '(':
  379. break
  380. optionStart = i
  381. elif optionStart == i-1:
  382. if c != '*':
  383. break
  384. elif c == ')':
  385. let name = pattern[optionStart+2 .. i-1]
  386. if equals or name in SkipOptions:
  387. result.pattern.add pattern[optionStart .. i]
  388. elif PcreOptions.hasKey name:
  389. result.flags = result.flags or PcreOptions[name]
  390. elif name == "NO_STUDY":
  391. result.study = false
  392. else:
  393. break
  394. optionStart = i+1
  395. equals = false
  396. elif not equals:
  397. if c == '=':
  398. equals = true
  399. if pattern[optionStart+2 .. i] notin SkipOptions:
  400. break
  401. elif c notin {'A'..'Z', '0'..'9', '_'}:
  402. break
  403. result.pattern.add pattern[optionStart .. pattern.high]
  404. proc re*(pattern: string): Regex =
  405. let (pattern, flags, study) = extractOptions(pattern)
  406. initRegex(pattern, flags, study)
  407. proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Option[RegexMatch] =
  408. var myResult = RegexMatch(pattern: pattern, str: str)
  409. # See PCRE man pages.
  410. # 2x capture count to make room for start-end pairs
  411. # 1x capture count as slack space for PCRE
  412. let vecsize = (pattern.captureCount() + 1) * 3
  413. # div 2 because each element is 2 cints long
  414. # plus 1 because we need the ceiling, not the floor
  415. myResult.pcreMatchBounds = newSeq[HSlice[cint, cint]]((vecsize + 1) div 2)
  416. myResult.pcreMatchBounds.setLen(vecsize div 3)
  417. let strlen = if endpos == int.high: str.len else: endpos+1
  418. doAssert(strlen <= str.len) # don't want buffer overflows
  419. let execRet = pcre.exec(pattern.pcreObj,
  420. pattern.pcreExtra,
  421. cstring(str),
  422. cint(strlen),
  423. cint(start),
  424. cint(flags),
  425. cast[ptr cint](addr myResult.pcreMatchBounds[0]),
  426. cint(vecsize))
  427. if execRet >= 0:
  428. return some(myResult)
  429. case execRet:
  430. of pcre.ERROR_NOMATCH:
  431. return none(RegexMatch)
  432. of pcre.ERROR_NULL:
  433. raise newException(AccessViolationDefect, "Expected non-null parameters")
  434. of pcre.ERROR_BADOPTION:
  435. raise RegexInternalError(msg: "Unknown pattern flag. Either a bug or " &
  436. "outdated PCRE.")
  437. of pcre.ERROR_BADUTF8, pcre.ERROR_SHORTUTF8, pcre.ERROR_BADUTF8_OFFSET:
  438. raise InvalidUnicodeError(msg: "Invalid unicode byte sequence",
  439. pos: myResult.pcreMatchBounds[0].a)
  440. else:
  441. raise RegexInternalError(msg: "Unknown internal error: " & $execRet)
  442. proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] =
  443. ## Like `find(...)<#find,string,Regex,int>`_, but anchored to the start of the
  444. ## string.
  445. runnableExamples:
  446. assert "foo".match(re"f").isSome
  447. assert "foo".match(re"o").isNone
  448. assert "abc".match(re"(\w)").get.captures[0] == "a"
  449. assert "abc".match(re"(?<letter>\w)").get.captures["letter"] == "a"
  450. assert "abc".match(re"(\w)\w").get.captures[-1] == "ab"
  451. assert "abc".match(re"(\w)").get.captureBounds[0] == 0 .. 0
  452. assert 0 in "abc".match(re"(\w)").get.captureBounds
  453. assert "abc".match(re"").get.captureBounds[-1] == 0 .. -1
  454. assert "abc".match(re"abc").get.captureBounds[-1] == 0 .. 2
  455. return str.matchImpl(pattern, start, endpos, pcre.ANCHORED)
  456. iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): RegexMatch =
  457. ## Works the same as `find(...)<#find,string,Regex,int>`_, but finds every
  458. ## non-overlapping match:
  459. runnableExamples:
  460. import std/sugar
  461. assert collect(for a in "2222".findIter(re"22"): a.match) == @["22", "22"]
  462. # not @["22", "22", "22"]
  463. ## Arguments are the same as `find(...)<#find,string,Regex,int>`_
  464. ##
  465. ## Variants:
  466. ##
  467. ## - `proc findAll(...)` returns a `seq[string]`
  468. # see pcredemo for explanation => https://www.pcre.org/original/doc/html/pcredemo.html
  469. let matchesCrLf = pattern.matchesCrLf()
  470. let unicode = uint32(getinfo[culong](pattern, pcre.INFO_OPTIONS) and
  471. pcre.UTF8) > 0u32
  472. let strlen = if endpos == int.high: str.len else: endpos+1
  473. var offset = start
  474. var match: Option[RegexMatch]
  475. var neverMatched = true
  476. while true:
  477. var flags = 0
  478. if match.isSome and
  479. match.get.matchBounds.a > match.get.matchBounds.b:
  480. # 0-len match
  481. flags = pcre.NOTEMPTY_ATSTART
  482. match = str.matchImpl(pattern, offset, endpos, flags)
  483. if match.isNone:
  484. # either the end of the input or the string
  485. # cannot be split here - we also need to bail
  486. # if we've never matched and we've already tried to...
  487. if flags == 0 or offset >= strlen or neverMatched: # All matches found
  488. break
  489. if matchesCrLf and offset < (str.len - 1) and
  490. str[offset] == '\r' and str[offset + 1] == '\L':
  491. # if PCRE treats CrLf as newline, skip both at the same time
  492. offset += 2
  493. elif unicode:
  494. # XXX what about invalid unicode?
  495. offset += str.runeLenAt(offset)
  496. assert(offset <= strlen)
  497. else:
  498. offset += 1
  499. else:
  500. neverMatched = false
  501. offset = match.get.matchBounds.b + 1
  502. yield match.get
  503. proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] =
  504. ## Finds the given pattern in the string between the end and start
  505. ## positions.
  506. ##
  507. ## `start`
  508. ## : The start point at which to start matching. `|abc` is `0`;
  509. ## `a|bc` is `1`
  510. ##
  511. ## `endpos`
  512. ## : The maximum index for a match; `int.high` means the end of the
  513. ## string, otherwise it’s an inclusive upper bound.
  514. return str.matchImpl(pattern, start, endpos, 0)
  515. proc findAll*(str: string, pattern: Regex, start = 0, endpos = int.high): seq[string] =
  516. result = @[]
  517. for match in str.findIter(pattern, start, endpos):
  518. result.add(match.match)
  519. proc contains*(str: string, pattern: Regex, start = 0, endpos = int.high): bool =
  520. ## Determine if the string contains the given pattern between the end and
  521. ## start positions:
  522. ## This function is equivalent to `isSome(str.find(pattern, start, endpos))`.
  523. runnableExamples:
  524. assert "abc".contains(re"bc")
  525. assert not "abc".contains(re"cd")
  526. assert not "abc".contains(re"a", start = 1)
  527. return isSome(str.find(pattern, start, endpos))
  528. proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] =
  529. ## Splits the string with the given regex. This works according to the
  530. ## rules that Perl and Javascript use.
  531. ##
  532. ## `start` behaves the same as in `find(...)<#find,string,Regex,int>`_.
  533. ##
  534. runnableExamples:
  535. # - If the match is zero-width, then the string is still split:
  536. assert "123".split(re"") == @["1", "2", "3"]
  537. # - If the pattern has a capture in it, it is added after the string
  538. # split:
  539. assert "12".split(re"(\d)") == @["", "1", "", "2", ""]
  540. # - If `maxsplit != -1`, then the string will only be split
  541. # `maxsplit - 1` times. This means that there will be `maxsplit`
  542. # strings in the output seq.
  543. assert "1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]
  544. result = @[]
  545. var lastIdx = start
  546. var splits = 0
  547. var bounds = 0 .. -1
  548. var never_ran = true
  549. for match in str.findIter(pattern, start = start):
  550. never_ran = false
  551. # bounds are inclusive:
  552. #
  553. # 0123456
  554. # ^^^
  555. # (1, 3)
  556. bounds = match.matchBounds
  557. # "12".split("") would be @["", "1", "2"], but
  558. # if we skip an empty first match, it's the correct
  559. # @["1", "2"]
  560. if bounds.a <= bounds.b or bounds.a > start:
  561. result.add(str.substr(lastIdx, bounds.a - 1))
  562. splits += 1
  563. lastIdx = bounds.b + 1
  564. for cap in match.captures:
  565. # if there are captures, include them in the result
  566. if cap.isSome:
  567. result.add(cap.get)
  568. if splits == maxSplit - 1:
  569. break
  570. # "12".split("\b") would be @["1", "2", ""], but
  571. # if we skip an empty last match, it's the correct
  572. # @["1", "2"]
  573. # If matches were never found, then the input string is the result
  574. if bounds.a <= bounds.b or bounds.b < str.high or never_ran:
  575. # last match: Each match takes the previous substring,
  576. # but "1 2".split(/ /) needs to return @["1", "2"].
  577. # This handles "2"
  578. result.add(str.substr(bounds.b + 1, str.high))
  579. template replaceImpl(str: string, pattern: Regex,
  580. replacement: untyped) {.dirty.} =
  581. # XXX seems very similar to split, maybe I can reduce code duplication
  582. # somehow?
  583. result = ""
  584. var lastIdx = 0
  585. for match {.inject.} in str.findIter(pattern):
  586. let bounds = match.matchBounds
  587. result.add(str.substr(lastIdx, bounds.a - 1))
  588. let nextVal = replacement
  589. result.add(nextVal)
  590. lastIdx = bounds.b + 1
  591. result.add(str.substr(lastIdx, str.len - 1))
  592. return result
  593. proc replace*(str: string, pattern: Regex,
  594. subproc: proc (match: RegexMatch): string): string =
  595. ## Replaces each match of Regex in the string with `subproc`, which should
  596. ## never be or return `nil`.
  597. ##
  598. ## If `subproc` is a `proc (RegexMatch): string`, then it is executed with
  599. ## each match and the return value is the replacement value.
  600. ##
  601. ## If `subproc` is a `proc (string): string`, then it is executed with the
  602. ## full text of the match and the return value is the replacement value.
  603. ##
  604. ## If `subproc` is a string, the syntax is as follows:
  605. ##
  606. ## - `$$` - literal `$`
  607. ## - `$123` - capture number `123`
  608. ## - `$foo` - named capture `foo`
  609. ## - `${foo}` - same as above
  610. ## - `$1$#` - first and second captures
  611. ## - `$#` - first capture
  612. ## - `$0` - full match
  613. ##
  614. ## If a given capture is missing, `IndexDefect` thrown for un-named captures
  615. ## and `KeyError` for named captures.
  616. replaceImpl(str, pattern, subproc(match))
  617. proc replace*(str: string, pattern: Regex,
  618. subproc: proc (match: string): string): string =
  619. replaceImpl(str, pattern, subproc(match.match))
  620. proc replace*(str: string, pattern: Regex, sub: string): string =
  621. # - 1 because the string numbers are 0-indexed
  622. replaceImpl(str, pattern,
  623. formatStr(sub, match.captures[name], match.captures[id - 1]))
  624. proc escapeRe*(str: string): string {.gcsafe.} =
  625. ## Escapes the string so it doesn't match any special characters.
  626. ## Incompatible with the Extra flag (`X`).
  627. ##
  628. ## Escaped char: `\ + * ? [ ^ ] $ ( ) { } = ! < > | : -`
  629. runnableExamples:
  630. assert escapeRe("fly+wind") == "fly\\+wind"
  631. assert escapeRe("!") == "\\!"
  632. assert escapeRe("nim*") == "nim\\*"
  633. #([\\+*?[^\]$(){}=!<>|:-])
  634. const SpecialCharMatcher = {'\\', '+', '*', '?', '[', '^', ']', '$', '(',
  635. ')', '{', '}', '=', '!', '<', '>', '|', ':',
  636. '-'}
  637. for c in items(str):
  638. case c
  639. of SpecialCharMatcher:
  640. result.add("\\")
  641. result.add(c)
  642. else:
  643. result.add(c)