How to use xregexp

Comprehensive xregexp code examples:

How to use xregexp.union:

68
69
70
71
72
73
74
75
76
77
]);
console.log(result); // -> ['xregexp.com', 'www.google.com']

// Merge strings and regexes into a single pattern with updated backreferences
// http://xregexp.com/api/#union
var merge = XRegExp.union(['a+b*c', /(dog)\1/, /(cat)\1/], 'i');
// Patterns can be provided as regex objects or strings. 
// Metacharacters are escaped in patterns provided as strings.
// Backreferences in provided regex objects are automatically renumbered 
// to work correctly within the larger combined pattern. 

How to use xregexp.isRegExp:

27
28
29
30
31
32
33
34
35
36
const nonCapturingGroup = (content = '') => `(?:${content})`;

const anchors = /^\^|\$$/g;

const processInterpolation = v =>
    XRegExp.isRegExp(v)
        ? nonCapturingGroup(v.source.replace(anchors, ''))
        : nonCapturingGroup(XRegExp.escape(v));

const regex = (flags) => (s, ...args) =>

How to use xregexp.escape:

136
137
138
139
140
141
142
143
144
145


// See http://eloquentjavascript.net/09_regexp.html Dynamically creating RegExp objects
let name = "dea+hl[]rd";
let text = "This dea+hl[]rd guy is super annoying.";
let escaped = XRegExp.escape(name);
let regexp = new RegExp("\\b" + escaped + "\\b", "gi");
console.log(text.replace(regexp, "_$&_"));
// → This _dea+hl[]rd_ guy is super annoying.
//

How to use xregexp.match:

80
81
82
83
84
85
86
87
88
89

result = XRegExp.match('... catcat ...', merge);
console.log(result); // catcat
result = XRegExp.match('dogDOG', merge);
console.log(result); // dogDOG
result = XRegExp.match('... a+b*c ...', merge);
console.log(result); // a+b*c

// http://xregexp.com/api/#matchRecursive
var str = '(t((e))s)t()(ing)';

How to use xregexp.replace:

96
97
98
99
100
101
102
103
104
105
function tmpl(c) {
  return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' ';
}
;
let template = str.slice(0, length + 1);
template = XRegExp.replace(template, regex, tmpl);
// 'Hello, world' -> 'HellAA AAAAA'
if (template.slice(template.length - 2).match(/\w\w/)) {
  template = template.replace(/\s*\S+$/, '');
} else {

How to use xregexp.matchChain:

53
54
55
56
57
58
59
60
61
62
// Extract every other digit from a string using XRegExp.forEach
XRegExp.forEach('1a2345', /\d/, function(match, i) {
    if (i % 2) this.push(+match[0]);
}, []); // -> [2, 4]

// Get numbers within <b> tags using XRegExp.matchChain
XRegExp.matchChain('1 <b>2</b> 3 <b>4 a 56</b>', [
    XRegExp('(?is)<b>.*?</b>'),
    /\d+/
]); // -> ['2', '4', '56']

How to use xregexp.forEach:

48
49
50
51
52
53
54
55
56
'2012-02-22'.replace(date, function(match) {
    return match.month + '/' + match.day + '/' + match.year;
}); // -> '02/22/2012'
date.exec('2012-02-22').year; // -> '2012'

// Extract every other digit from a string using XRegExp.forEach
XRegExp.forEach('1a2345', /\d/, function(match, i) {
    if (i % 2) this.push(+match[0]);
}, []); // -> [2, 4]

How to use xregexp.tag:

144
145
146
147
148
149
150
151
152
153
Provides tagged template literals that create regexes with XRegExp syntax and flags:

```js
const h12 = /1[0-2]|0?[1-9]/;
const h24 = /2[0-3]|[01][0-9]/;
const hours = XRegExp.tag('x')`${h12} : | ${h24}`;
const minutes = /^[0-5][0-9]$/;
// Note that explicitly naming the 'minutes' group is required for named backreferences
const time = XRegExp.tag('x')`^ ${hours} (?<minutes>${minutes}) $`;
time.test('10:59'); // -> true

How to use xregexp.matchRecursive:

146
147
148
149
150
151
152
153
154
155

Named subpatterns can be provided as strings or regex objects. A leading `^` and trailing unescaped `$` are stripped from subpatterns if both are present, which allows embedding independently-useful anchored patterns. `{{…}}` tokens can be quantified as a single unit. Any backreferences in the outer pattern or provided subpatterns are automatically renumbered to work correctly within the larger combined pattern. The syntax `({{name}})` works as shorthand for named capture via `(?<name>{{name}})`. Named subpatterns cannot be embedded within character classes.

See also: *[Creating Grammatical Regexes Using XRegExp.build](http://blog.stevenlevithan.com/archives/grammatical-patterns-xregexp-build)*.

### XRegExp.matchRecursive

In browsers, first include the script:

```html

How to use xregexp.build:

118
119
120
121
122
123
124
125
126
127

Opting in to astral mode disables the use of `\p{…}` and `\P{…}` within character classes. In astral mode, use e.g. `(\pL|[0-9_])+` instead of `[\pL0-9_]+`.

XRegExp uses Unicode 6.2.0.

### XRegExp.build

In browsers, first include the script:

```html

How to use xregexp.exec:

17
18
19
20
21
22
23
24
25
26
var date = XRegExp('(?<year>  [0-9]{4} ) -?  # year  \n\
                    (?<month> [0-9]{2} ) -?  # month \n\
                    (?<day>   [0-9]{2} )     # day   ', 'x');

// XRegExp.exec gives you named backreferences on the match result
var match = XRegExp.exec('2012-02-22', date);
match.year; // -> '2012'

// It also includes optional pos and sticky arguments
var pos = 3, result = [];