regex.ts 954 B

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * Escapes special regex characters in a string.
  3. * @param text The string to transform
  4. * @returns Escaped string
  5. */
  6. export const regexEscape = (text: string) =>
  7. text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
  8. export type RegexMatch = {
  9. matchString: string
  10. startIndex: number
  11. endIndex: number
  12. }
  13. /**
  14. * Returns all the regex match ranges for a given input
  15. * @param regex The Regular Expression to find from
  16. * @param input The input string to get match ranges from
  17. * @returns An array of `RegexMatch` objects giving info about the matches
  18. */
  19. export const regexFindAllMatches = (regex: RegExp) => (input: string) => {
  20. const matches: RegexMatch[] = []
  21. // eslint-disable-next-line no-cond-assign, prettier/prettier
  22. for (let match; match = regex.exec(input); match !== null)
  23. matches.push({
  24. matchString: match[0],
  25. startIndex: match.index,
  26. endIndex: match.index + match[0].length - 1,
  27. })
  28. return matches
  29. }