nre.nim 26 KB

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