Skip to content

Get all matches of a regexp with corresponding start and end positions

Notifications You must be signed in to change notification settings

Lavaei/sharp-regex

This branch is 11 commits ahead of, 5 commits behind valoricDe/MultiRegExp2:master.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

2347659 · Mar 25, 2019

History

29 Commits
Oct 1, 2017
Mar 25, 2019
Mar 25, 2019
Mar 7, 2019
Mar 7, 2019
Mar 25, 2019
Mar 25, 2019
Mar 24, 2019

Repository files navigation

sharp-regex

This class gets all matches, with start and end position, within the string, for a given regex.

From high level the source code is:

  1. Ensuring that each character is captured by a group: eg. /ab(cd)ef/ => /(ab)(cd)(ef)/
  2. Calling exec on the converted regexp with a given string
  3. Summing lengths of previous groups for start position of current group, add length of current group for end position

API

SharpRegex(baseRegExp: Regexp)

will setup parsed regexp, returns instance

getFullDetails(subject: string)

will find the full match and all matching groups, returns {match: string, start: number, end: number, group: number}[]

getGroupsDetails(subject: string)

will find all matching groups, returns {match: string, start: number, end: number, group: number}[]

getGroupDetails(subject: string, group:number)

will find given group details, returns {match: string, start: number, end: number}

Usage

let sharpRegex = new SharpRegex(/a(?: )bc(def(ghi)xyz)/g),
    result = sharpRegex.getFullDetails('ababa bcdefghixyzXXXX');

console.log(result);

Will output:

/**
 * [
 *  [ 
 *   { match: 'a bcdefghixyz', start: 4, end: 17, group: 0 },
 *   { match: 'defghixyz', start: 8, end: 17, group: 1 },
 *   { match: 'ghi', start: 11, end: 14, group: 2 } 
 *  ]
 * ]
 */

To get just groups details:

let matches = sharpRegex.getGroupsDetails('ababa bcdefghixyzXXXX');

/**
 * [
 *  [ 
 *   { match: 'defghixyz', start: 8, end: 17, group: 1 },
 *   { match: 'ghi', start: 11, end: 14, group: 2 } 
 *  ]
 * ]
 */

To get just given group details:

let matches = sharpRegex.getGroupDetails('ababa bcdefghixyzXXXX', 2);

/**
 * [
 *  { match: 'ghi', start: 11, end: 14 }
 * ]
 */

About

Get all matches of a regexp with corresponding start and end positions

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 100.0%