🕹️Installation and use
npm install regexpert
What is needed for work
1. Register plugin
// vite.config.ts
import { regExpertVitePlugin } from 'regexpert';
export default defineConfig(() => {
return {
plugins: [regExpertVitePlugin()],
};
});
2. Start a project
npm run dev
Type parsing occurs only when the project is running!
3. Write your RegExp
// your-file.ts
import { makeNamedRegExp } from 'regexpert';
const { regExp: myFavouriteRegExp, transform: transformMyFavouriteRegExp } = makeNamedRegExp(
`/(1)\\s?text between\\s(?<groupName>named group)( )?\\k<groupName>?/`,
);
// There will be a conversion to such RegExp - this will work in browsers in IOS
console.info(regExp); // /(1)\s?text between\s(named group)?( )?\2/
What is the main task?
// Let's find a suitable line:
const matches = '1text between named group'.match(myFavouriteRegExp);
// [
// '1text between named group ',
// '1',
// 'named group',
// ' '
// ]
// Let's pass the result to the transform function
const result = transformMyFavouriteRegExp(matches);
console.info(result);
// {
// '$0': '1text between named group ',
// '$1': '1',
// groupName: 'named group',
// '$3': ' '
// }
type Result = typeof result;
// Result is {
// $0: `1${string | ''}text between${string}named group${' ' | ''}${'named group' | ''}`,
// $1: '1',
// groupName: 'named group',
// $3?: ' ',
// }
What do we get?
- Convenient use of the transformed object
- We get the expected types for each field
- We know for sure which field will be optional
Every time you make a change, files with your types will be automatically generated, which you can always view and inspect.
Format
Use only forward quotation (`) marks when writing StrRegExp
const { regExp } = makeNamedRegExp(`/HI(?: World)/ig`);
But it won't work like that
const { regExp } = makeNamedRegExp('/HI(?: World)/ig');