nre.nim 26 KB

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