string-extractor v0.0.1
string-extractor.js  
  
 
Regular expression sugar for getting data out of strings.
Usage
var stringExtractor = require('string-extractor');
var pattern = '*/{{ year: 4d }}-{{ month: d }}-{{ slug }}.((txt|m*))';
var extract = stringExtractor(pattern);
extract('foo/2014-01-bar.txt');      //=> { year: '2014', month: '01', slug: 'bar' }
extract('foo/2014-01-bar.md');       //=> { year: '2014', month: '01', slug: 'bar' }
extract('foo/2014-01-bar.markdown'); //=> { year: '2014', month: '01', slug: 'bar' }
extract('foo'); //=> false- A - *represents a wildcard, which matches one or more characters. We can have consecutive wildcards. For example,- ***represents a sequence of three or more characters.
- Enclose option groups in - ((brackets- )). An option group matches any one of the specified strings separated by a pipe- |. Each string can contain wildcards. As in our example,- ((m*|txt))matches- txt,- md, and- markdown.
- Enclose capturing groups in - {{curly braces- }}. A capturing group comprises a name and an optional- printf-like “formatter”. If specified, the formatter must be preceded by a colon- :. Each formatter comprises a length and a “type”. A- dtype means one or more digits, while an- stype means one or more characters (including digits). Some examples of valid formatters:- Type only — d,s
- Length only — 4
- Both — 4d,4s
 
- Type only — 
- If the given pattern does not contain any capturing groups, matching it with a - strwill return:- trueif- strmatches the pattern, and
- falseotherwise.
 - If the given pattern contains at least one capturing group, matching it with a - strwill return:- an object literal of values extracted from the strifstrmatches the pattern, and
- falseotherwise.
 
- Matching is case-sensitive. Set - opts.ignoreCaseto- trueto enable case-insensitive matching:- var pattern = '{{ title }}.jpg'; var opts = { ignoreCase: true }; var extract = stringExtractor(pattern, opts); extract('foo.jpg'); //=> { title: 'foo' } extract('foo.JPG'); //=> { title: 'foo' }
Read the tests for more usage examples.
API
var stringExtractor = require('string-extractor');var extract = stringExtractor(pattern , opts)
Compiles the specified string pattern into a regular expression. opts is an object literal; set opts.ignoreCase to true to enable case-insensitive matching.
var results = extract(str)
extract is a function that uses the compiled regular expression to extract values from the specified str. It returns an object literal, with the extracted values keyed to the names of the capturing groups.
Installation
Install via npm:
$ npm i --save string-extractorChangelog
- 0.0.1- Initial release
 
License
10 years ago