Function defineToken

  • Define a custom token that can be used in conjunction with other tokens. For a detailed guide on custom tokens, please read https://github.com/hlysine/readable-regexp#custom-tokens

    Notes:

    • TypeScript users should extend the RegExpToken interface to add their own custom tokens before calling this function.
    • The token name must be a valid JavaScript identifier.
    • The token name must not conflict with any existing properties of RegExpToken.
    • All custom tokens should be defined before any tokens are used to build regular expressions.

    Type Parameters

    Parameters

    • tokenName: Name

      The name of the custom token. In TypeScript, it needs to be defined in the RegExpToken interface.

    • config: Check extends true
          ? CustomTokenConfig<RegExpToken[Name]>
          : {
              error: "Invalid token type: tokens should intersect the RegExpToken type if they are constant, or the IncompleteToken type if they are dynamic.";
          }

      The configuration for the custom token. Implement the constant method to return a constant token, or the dynamic method for a token that accepts arguments. Implement both for a mixed token.

    Returns Check extends true
        ? RegExpToken[Name]
        : never

    The custom token

    Example

    Create a constant token

    Extend the RegExpToken interface to add a new token:

    import { RegExpToken } from 'readable-regexp';

    declare module 'readable-regexp' {
    interface RegExpToken {
    severity: RegExpToken;
    }
    }

    Implement the custom token:

    const severity = defineToken('severity', {
    constant(this: RegExpToken) {
    return this.oneOf`error` `warning` `info` `debug`;
    },
    });

    Use the custom token:

    // Referencing the token returned by the defineToken function
    console.log(severity.toString()); // (?:error|warning|info|debug)

    // Referencing the token in an expression
    console.log(lineStart.severity.lineEnd.toString()); // ^(?:error|warning|info|debug)$

Generated using TypeDoc