regex-each
Iterate matches in a string using a JavaScript regular expression
Written in typescript targeting ES2015 JavaScript.
Installation
npm install regex-each
Usage
JavaScript:
const regexEach =
Typescript:
Example
// Parse words and numbers.regexEach/|/i, '10 apples for 5 dollars', console.log'nums:', numsconsole.log'words:', words
Output:
nums: [ 10, 5 ]
words: [ 'apples', 'for', 'dollars' ]
Signature
regexEach expr: RegExp|string, str: string, onMatch:void void
expr
: a regular expression or a string.
- If
expr
is a regular expression, it remains unmodified -- an internal copy is made byregex-each
. If nosticky
orglobal
flag is set onexpr
, theglobal
flag is added automatically. - If
expr
is a string, it is converted to a regular expression and theglobal
flag is added automatically. There is no way to add other flags when a string is used. If you need flags, create and pass aRegExp
object.
str
: the string to iterate matches on.
onMatch
: called for each match. The match
parameter is the regular expression exec
result, and the regex
parameter is the regular expression used for matching.
RegExp.prototype.each
While monkey-patching globals isn't recommended, it's possible to add regex-each
functionality to the RegExp
prototype:
declare global RegExp.prototype.each = re.each'10 apples for 5 dollars',
Output:
undefined '10'apples undefinedfor undefinedundefined '5'dollars undefined
More Examples
Parse command-line arguments
// Define tokens used by the parser. // Create the parser. /** * Parse an argument string. */ console.logargs
Output:
name: '$default' values: 'each' name: 'nums' values: '1' '2' '3' name: 'alpha' values: 'abc' 'def' 'g'
Parse configuration files
// Define tokens used by the parser. // Create the parser. /** * Create and return a context object. */ /** * Parse a configuration file. */ console.logitems
Output:
name: '$global' keyVals: read: true values: 'float' 'fly' name: 'options' keyVals: size: 5 root: './data' haltOnError: false values: name: 'fruits' keyVals: {} values: 'apples' 'cherries' 'raspberries'