| [81bc7da] | 1 | # balanced-match
|
|---|
| 2 |
|
|---|
| 3 | Match balanced string pairs, like `{` and `}` or `<b>` and
|
|---|
| 4 | `</b>`. Supports regular expressions as well!
|
|---|
| 5 |
|
|---|
| 6 | ## Example
|
|---|
| 7 |
|
|---|
| 8 | Get the first matching pair of braces:
|
|---|
| 9 |
|
|---|
| 10 | ```js
|
|---|
| 11 | import { balanced } from 'balanced-match'
|
|---|
| 12 |
|
|---|
| 13 | console.log(balanced('{', '}', 'pre{in{nested}}post'))
|
|---|
| 14 | console.log(balanced('{', '}', 'pre{first}between{second}post'))
|
|---|
| 15 | console.log(
|
|---|
| 16 | balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'),
|
|---|
| 17 | )
|
|---|
| 18 | ```
|
|---|
| 19 |
|
|---|
| 20 | The matches are:
|
|---|
| 21 |
|
|---|
| 22 | ```bash
|
|---|
| 23 | $ node example.js
|
|---|
| 24 | { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
|
|---|
| 25 | { start: 3,
|
|---|
| 26 | end: 9,
|
|---|
| 27 | pre: 'pre',
|
|---|
| 28 | body: 'first',
|
|---|
| 29 | post: 'between{second}post' }
|
|---|
| 30 | { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
|
|---|
| 31 | ```
|
|---|
| 32 |
|
|---|
| 33 | ## API
|
|---|
| 34 |
|
|---|
| 35 | ### const m = balanced(a, b, str)
|
|---|
| 36 |
|
|---|
| 37 | For the first non-nested matching pair of `a` and `b` in `str`, return an
|
|---|
| 38 | object with those keys:
|
|---|
| 39 |
|
|---|
| 40 | - **start** the index of the first match of `a`
|
|---|
| 41 | - **end** the index of the matching `b`
|
|---|
| 42 | - **pre** the preamble, `a` and `b` not included
|
|---|
| 43 | - **body** the match, `a` and `b` not included
|
|---|
| 44 | - **post** the postscript, `a` and `b` not included
|
|---|
| 45 |
|
|---|
| 46 | If there's no match, `undefined` will be returned.
|
|---|
| 47 |
|
|---|
| 48 | 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', '}']`.
|
|---|
| 49 |
|
|---|
| 50 | ### const r = balanced.range(a, b, str)
|
|---|
| 51 |
|
|---|
| 52 | For the first non-nested matching pair of `a` and `b` in `str`, return an
|
|---|
| 53 | array with indexes: `[ <a index>, <b index> ]`.
|
|---|
| 54 |
|
|---|
| 55 | If there's no match, `undefined` will be returned.
|
|---|
| 56 |
|
|---|
| 57 | 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]`.
|
|---|