string-extractor
v0.0.1
Published
Regular expression sugar for getting data out of strings.
Downloads
75
Maintainers
Readme
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))
matchestxt
,md
, andmarkdown
.Enclose capturing groups in
{{
curly braces}}
. A capturing group comprises a name and an optionalprintf
-like “formatter”. If specified, the formatter must be preceded by a colon:
. Each formatter comprises a length and a “type”. Ad
type means one or more digits, while ans
type 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
str
will return:true
ifstr
matches the pattern, andfalse
otherwise.
If the given pattern contains at least one capturing group, matching it with a
str
will return:- an object literal of values extracted from the
str
ifstr
matches the pattern, and false
otherwise.
Matching is case-sensitive. Set
opts.ignoreCase
totrue
to 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-extractor
Changelog
- 0.0.1
- Initial release