|
| 1 | +# structured-regex |
| 2 | + |
| 3 | +[](https://github.com/readmeio/structured-regex/) [](https://npm.im/structured-regex) |
| 4 | + |
| 5 | +[](https://readme.io) |
| 6 | + |
| 7 | +`structured-regex` is a wrapper for [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) that allows you to do named group parsing without having to use actually [named capture groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group). |
| 8 | + |
| 9 | +Why not use named capture groups? If you're composing a complicated regex by interpolating other regex patterns into it if any of those patterns contain a named capture that group may either only partially match the pattern they're inserted into, or if their name is reused then the regex will throw an error. |
| 10 | + |
| 11 | +For example on a `/projects/me` URI with a regex to match it of `/projects/(me|${PROJECT_SUBDOMAIN.regex.source})` you can't have `?<subdomain>` inside of the `PROJECT_SUBDOMAIN` regex because `me` wouldn't be placed into our matched `subdomain` group. |
| 12 | + |
| 13 | +`structured-regex` not only allows you to formally define the expected typings of our matches but you can supply it a mapping object to coorelate your named group with the index that it's captured against. |
| 14 | + |
| 15 | +## 📦 Installation |
| 16 | + |
| 17 | +```sh |
| 18 | +npm install --save structured-regex |
| 19 | +``` |
| 20 | + |
| 21 | +## 🧰 Usage |
| 22 | + |
| 23 | +```ts |
| 24 | +import { StructuredRegEx } from 'structured-regex'; |
| 25 | + |
| 26 | +const SEMVER_REGEX = /([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?(-.*)?/; |
| 27 | +const SLUG_REGEX = /[a-z0-9-_ ]+/i; |
| 28 | + |
| 29 | +const VERSION_REGEX = new RegExp(`stable|${SEMVER_REGEX.source}`, 'i'); |
| 30 | +const API_FILENAME_REGEX = new RegExp(`(${SLUG_REGEX.source}.(json|yaml|yml))`, 'i'); |
| 31 | + |
| 32 | +const API_URI_REGEX = new StructuredRegEx<{ filename: string; version: string }>( |
| 33 | + new RegExp(`/versions/(${VERSION_REGEX.source})/apis/(${API_FILENAME_REGEX.source})`, 'i'), |
| 34 | + { |
| 35 | + version: 1, |
| 36 | + filename: 6, // `filename` is in the `matches[6]` spot of a valid match |
| 37 | + }, |
| 38 | +); |
| 39 | + |
| 40 | +console.log(API_URI_REGEX.parse('/versions/stable/apis/petstore.json')); |
| 41 | +// ➪ { version: 'stable', filename: 'petstore.json' } |
| 42 | +``` |
| 43 | + |
| 44 | +You can also supply it non-`RegExp` regexes as well. |
| 45 | + |
| 46 | +```ts |
| 47 | +const API_URI_REGEX = new StructuredRegEx<{ filename: string; version: string }>(/\/versions\/(.*)\/apis\/(.*)/i, { |
| 48 | + version: 1, |
| 49 | + filename: 2, |
| 50 | +}); |
| 51 | + |
| 52 | +console.log(API_URI_REGEX.parse('/versions/stable/apis/petstore.json')); |
| 53 | +// ➪ { version: 'stable', filename: 'petstore.json' } |
| 54 | +``` |
0 commit comments