0d9a51b4b14644a1461a972b725c1c14f6251bb41af6b560d2990db811aba5c01be0bbce9baa26324a7de32467e5c5c0d8e74f7a0f75018962cb99fbaec580 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # @isaacs/balanced-match
  2. A hybrid CJS/ESM TypeScript fork of
  3. [balanced-match](http://npm.im/balanced-match).
  4. Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!
  5. [![CI](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml/badge.svg)](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml)
  6. [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)
  7. ## Example
  8. Get the first matching pair of braces:
  9. ```js
  10. import { balanced } from '@isaacs/balanced-match'
  11. console.log(balanced('{', '}', 'pre{in{nested}}post'))
  12. console.log(balanced('{', '}', 'pre{first}between{second}post'))
  13. console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'))
  14. ```
  15. The matches are:
  16. ```bash
  17. $ node example.js
  18. { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
  19. { start: 3,
  20. end: 9,
  21. pre: 'pre',
  22. body: 'first',
  23. post: 'between{second}post' }
  24. { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
  25. ```
  26. ## API
  27. ### const m = balanced(a, b, str)
  28. For the first non-nested matching pair of `a` and `b` in `str`, return an
  29. object with those keys:
  30. - **start** the index of the first match of `a`
  31. - **end** the index of the matching `b`
  32. - **pre** the preamble, `a` and `b` not included
  33. - **body** the match, `a` and `b` not included
  34. - **post** the postscript, `a` and `b` not included
  35. If there's no match, `undefined` will be returned.
  36. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.
  37. ### const r = balanced.range(a, b, str)
  38. For the first non-nested matching pair of `a` and `b` in `str`, return an
  39. array with indexes: `[ <a index>, <b index> ]`.
  40. If there's no match, `undefined` will be returned.
  41. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.