Skip to content

How to Use

Matteo Basso edited this page Dec 27, 2016 · 5 revisions

natural-regex exports only one class to make it works. Supposing a CommonJS environment you can import it as follows:

import NaturalRegex from 'natural-regex';

NaturalRegex is now an object with the following APIs

NaturalRegex.parser

This represents the native jison parser, normally, you haven't to use it.

NaturalRegex.parse(code: string)

Returns a string that represents the native regex corresponding to the natural-regex given as parameter.

const regexString = NaturalRegex.parse('starts with Lorem, then space and then foo or bar');
const regex = new RegExp(regexString);

NaturalRegex.from(code: string, flags: string or object)

Returns a RegExp Object corresponding to the natural-regex given as parameter with the given flags.

const LoremFooOrBar = NaturalRegex.from('starts with Lorem, then space and then foo or bar');
LoremFooOrBar.test('Lorem bar'); // this evaluates true

NaturalRegex.replace({ string: string, match: string, replace: string, flags = 'g': string or object })

Returns a new version of string with replaced matches, given from match natural-regex, with replace string. By default flags parameter is set to g, in this way all matches are replaced and not only the first.

const newString = NaturalRegex.replace({
  string: 'foo is awesome, foo!',
  match: 'starts with foo',
  replace: 'bar',
});
// newString === 'bar is awesome, foo!'

####Flags parameter

flags parameter can be a string or an object that contains informations about the RegExp that will be generated by natural-regex. If you want to pass a string, you can create any combination of the following values:

  • g: global match; find all matches rather than stopping after the first match
  • i: ignore case
  • m: multiline; treat start, starts with, end and ends with as working over multiple lines (i.e., match the beginning or end of each line, not only the very beginning or end of the whole input string)
  • u: unicode; treat pattern as a sequence of unicode code points. Enables unicode keyword
  • y: sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string. See this for more information

Here is an example:

// natural-regex with ignore case and multiple line flags (im)
NaturalRegex.from(
	'starts with Lorem, then space and then foo or bar',
	'im'
);

If you prefer, you can also pass an object as shown below.

// natural-regex with ignore case and multiple line flags (im)
NaturalRegex.from(
	'starts with Lorem, then space and then foo or bar',
	{
		global: false, // g flag
		ignoreCase: true, // i flag, active
		multiline: true, // m flag, active
		unicode: false, // u flag
		sticky: false, // y flag
	}
);