Installations
npm install xregexp
Developer Guide
Typescript
Yes
Module System
CommonJS, UMD
Node Version
16.3.0
NPM Version
7.5.2
Score
94.3
Supply Chain
99.6
Quality
78.2
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (96.45%)
TypeScript (2.32%)
HTML (1.23%)
Developer
Download Statistics
Total Downloads
1,634,249,094
Last Day
160,844
Last Week
1,917,672
Last Month
11,941,497
Last Year
161,068,849
GitHub Statistics
3,309 Stars
682 Commits
278 Forks
70 Watching
1 Branches
21 Contributors
Package Meta Information
Latest Version
5.1.1
Package Id
xregexp@5.1.1
Unpacked Size
794.73 kB
Size
202.52 kB
File Count
24
NPM Version
7.5.2
Node Version
16.3.0
Total Downloads
Cumulative downloads
Total Downloads
1,634,249,094
Last day
-70%
160,844
Compared to previous day
Last week
-32.6%
1,917,672
Compared to previous week
Last month
-15.3%
11,941,497
Compared to previous month
Last year
-45.5%
161,068,849
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
16
XRegExp 5.1.1
XRegExp provides augmented (and extensible) JavaScript regular expressions. You get modern syntax and flags beyond what browsers support natively. XRegExp is also a regex utility belt with tools to make your grepping and parsing easier, while freeing you from regex cross-browser inconsistencies and other annoyances.
XRegExp supports all native ES6 regular expression syntax. It supports ES5+ browsers, and you can use it with Node.js or as a RequireJS module. Over the years, many of XRegExp's features have been adopted by new JavaScript standards (named capturing, Unicode properties/scripts/categories, flag s
, sticky matching, etc.), so using XRegExp can be a way to extend these features into older browsers.
Performance
XRegExp compiles to native RegExp
objects. Therefore regexes built with XRegExp perform just as fast as native regular expressions. There is a tiny extra cost when compiling a pattern for the first time.
Named capture breaking change in XRegExp 5
XRegExp 5 introduced a breaking change where named backreference properties now appear on the result's groups
object (following ES2018), rather than directly on the result. To restore the old handling so you don't need to update old code, run the following line after importing XRegExp:
1XRegExp.uninstall('namespacing');
XRegExp 4.1.0 and later allow introducing the new behavior without upgrading to XRegExp 5 by running XRegExp.install('namespacing')
.
Following is the most commonly needed change to update code for the new behavior:
1// Change this 2const name = XRegExp.exec(str, regexWithNamedCapture).name; 3 4// To this 5const name = XRegExp.exec(str, regexWithNamedCapture).groups.name;
See below for more examples of using named capture with XRegExp.exec
and XRegExp.replace
.
Usage examples
1// Using named capture and flag x for free-spacing and line comments 2const date = XRegExp( 3 `(?<year> [0-9]{4} ) -? # year 4 (?<month> [0-9]{2} ) -? # month 5 (?<day> [0-9]{2} ) # day`, 'x'); 6 7// XRegExp.exec provides named backreferences on the result's groups property 8let match = XRegExp.exec('2021-02-22', date); 9match.groups.year; // -> '2021' 10 11// It also includes optional pos and sticky arguments 12let pos = 3; 13const result = []; 14while (match = XRegExp.exec('<1><2><3>4<5>', /<(\d+)>/, pos, 'sticky')) { 15 result.push(match[1]); 16 pos = match.index + match[0].length; 17} 18// result -> ['2', '3'] 19 20// XRegExp.replace allows named backreferences in replacements 21XRegExp.replace('2021-02-22', date, '$<month>/$<day>/$<year>'); 22// -> '02/22/2021' 23XRegExp.replace('2021-02-22', date, (...args) => { 24 // Named backreferences are on the last argument 25 const groups = args[args.length - 1]; 26 return `${groups.month}/${groups.day}/${groups.year}`; 27}); 28// -> '02/22/2021' 29 30// XRegExps compile to RegExps and work with native methods 31date.test('2021-02-22'); 32// -> true 33// However, named captures must be referenced using numbered backreferences 34// if used with native methods 35'2021-02-22'.replace(date, '$2/$3/$1'); 36// -> '02/22/2021' 37 38// Use XRegExp.forEach to extract every other digit from a string 39const evens = []; 40XRegExp.forEach('1a2345', /\d/, (match, i) => { 41 if (i % 2) evens.push(+match[0]); 42}); 43// evens -> [2, 4] 44 45// Use XRegExp.matchChain to get numbers within <b> tags 46XRegExp.matchChain('1 <b>2</b> 3 <B>4 \n 56</B>', [ 47 XRegExp('<b>.*?</b>', 'is'), 48 /\d+/ 49]); 50// -> ['2', '4', '56'] 51 52// You can also pass forward and return specific backreferences 53const html = 54 `<a href="https://xregexp.com/">XRegExp</a> 55 <a href="https://www.google.com/">Google</a>`; 56XRegExp.matchChain(html, [ 57 {regex: /<a href="([^"]+)">/i, backref: 1}, 58 {regex: XRegExp('(?i)^https?://(?<domain>[^/?#]+)'), backref: 'domain'} 59]); 60// -> ['xregexp.com', 'www.google.com'] 61 62// Merge strings and regexes, with updated backreferences 63XRegExp.union(['m+a*n', /(bear)\1/, /(pig)\1/], 'i', {conjunction: 'or'}); 64// -> /m\+a\*n|(bear)\1|(pig)\2/i
These examples give the flavor of what's possible, but XRegExp has more syntax, flags, methods, options, and browser fixes that aren't shown here. You can also augment XRegExp's regular expression syntax with addons (see below) or write your own. See xregexp.com for details.
Addons
You can either load addons individually, or bundle all addons with XRegExp by loading xregexp-all.js
from https://unpkg.com/xregexp/xregexp-all.js.
Unicode
If not using xregexp-all.js
, first include the Unicode Base script and then one or more of the addons for Unicode categories, properties, or scripts.
Then you can do this:
1// Test some Unicode scripts 2// Can also use the Script= prefix to match ES2018: \p{Script=Hiragana} 3XRegExp('^\\p{Hiragana}+$').test('ひらがな'); // -> true 4XRegExp('^[\\p{Latin}\\p{Common}]+$').test('Über Café.'); // -> true 5 6// Test the Unicode categories Letter and Mark 7// Can also use the short names \p{L} and \p{M} 8const unicodeWord = XRegExp.tag()`^\p{Letter}[\p{Letter}\p{Mark}]*$`; 9unicodeWord.test('Русский'); // -> true 10unicodeWord.test('日本語'); // -> true 11unicodeWord.test('العربية'); // -> true
By default, \p{…}
and \P{…}
support the Basic Multilingual Plane (i.e. code points up to U+FFFF
). You can opt-in to full 21-bit Unicode support (with code points up to U+10FFFF
) on a per-regex basis by using flag A
. This is called astral mode. You can automatically add flag A
for all new regexes by running XRegExp.install('astral')
. When in astral mode, \p{…}
and \P{…}
always match a full code point rather than a code unit, using surrogate pairs for code points above U+FFFF
.
1// Using flag A to match astral code points 2XRegExp('^\\p{S}$').test('💩'); // -> false 3XRegExp('^\\p{S}$', 'A').test('💩'); // -> true 4// Using surrogate pair U+D83D U+DCA9 to represent U+1F4A9 (pile of poo) 5XRegExp('^\\p{S}$', 'A').test('\uD83D\uDCA9'); // -> true 6 7// Implicit flag A 8XRegExp.install('astral'); 9XRegExp('^\\p{S}$').test('💩'); // -> true
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 14.0.0.
XRegExp.build
Build regular expressions using named subpatterns, for readability and pattern reuse:
1const time = XRegExp.build('(?x)^ {{hours}} ({{minutes}}) $', { 2 hours: XRegExp.build('{{h12}} : | {{h24}}', { 3 h12: /1[0-2]|0?[1-9]/, 4 h24: /2[0-3]|[01][0-9]/ 5 }), 6 minutes: /^[0-5][0-9]$/ 7}); 8 9time.test('10:59'); // -> true 10XRegExp.exec('10:59', time).groups.minutes; // -> '59'
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.
XRegExp.tag (included with XRegExp.build)
Provides tagged template literals that create regexes with XRegExp syntax and flags:
1XRegExp.tag()`\b\w+\b`.test('word'); // -> true 2 3const hours = /1[0-2]|0?[1-9]/; 4const minutes = /(?<minutes>[0-5][0-9])/; 5const time = XRegExp.tag('x')`\b ${hours} : ${minutes} \b`; 6time.test('10:59'); // -> true 7XRegExp.exec('10:59', time).groups.minutes; // -> '59' 8 9const backref1 = /(a)\1/; 10const backref2 = /(b)\1/; 11XRegExp.tag()`${backref1}${backref2}`.test('aabb'); // -> true
XRegExp.tag
does more than just interpolation. You get all the XRegExp syntax and flags, and since it reads patterns as raw strings, you no longer need to escape all your backslashes. XRegExp.tag
also uses XRegExp.build
under the hood, so you get all of its extras for free. Leading ^
and trailing unescaped $
are stripped from interpolated patterns if both are present (to allow embedding independently useful anchored regexes), interpolating into a character class is an error (to avoid unintended meaning in edge cases), interpolated patterns are treated as atomic units when quantified, interpolated strings have their special characters escaped, and any backreferences within an interpolated regex are rewritten to work within the overall pattern.
XRegExp.matchRecursive
A robust and flexible API for matching recursive constructs using XRegExp pattern strings as left and right delimiters:
1const str1 = '(t((e))s)t()(ing)'; 2XRegExp.matchRecursive(str1, '\\(', '\\)', 'g'); 3// -> ['t((e))s', '', 'ing'] 4 5// Extended information mode with valueNames 6const str2 = 'Here is <div> <div>an</div></div> example'; 7XRegExp.matchRecursive(str2, '<div\\s*>', '</div>', 'gi', { 8 valueNames: ['between', 'left', 'match', 'right'] 9}); 10/* -> [ 11{name: 'between', value: 'Here is ', start: 0, end: 8}, 12{name: 'left', value: '<div>', start: 8, end: 13}, 13{name: 'match', value: ' <div>an</div>', start: 13, end: 27}, 14{name: 'right', value: '</div>', start: 27, end: 33}, 15{name: 'between', value: ' example', start: 33, end: 41} 16] */ 17 18// Omitting unneeded parts with null valueNames, and using escapeChar 19const str3 = '...{1}.\\{{function(x,y){return {y:x}}}'; 20XRegExp.matchRecursive(str3, '{', '}', 'g', { 21 valueNames: ['literal', null, 'value', null], 22 escapeChar: '\\' 23}); 24/* -> [ 25{name: 'literal', value: '...', start: 0, end: 3}, 26{name: 'value', value: '1', start: 4, end: 5}, 27{name: 'literal', value: '.\\{', start: 6, end: 9}, 28{name: 'value', value: 'function(x,y){return {y:x}}', start: 10, end: 37} 29] */ 30 31// Sticky mode via flag y 32const str4 = '<1><<<2>>><3>4<5>'; 33XRegExp.matchRecursive(str4, '<', '>', 'gy'); 34// -> ['1', '<<2>>', '3'] 35 36// Skipping unbalanced delimiters instead of erroring 37const str5 = 'Here is <div> <div>an</div> unbalanced example'; 38XRegExp.matchRecursive(str5, '<div\\s*>', '</div>', 'gi', { 39 unbalanced: 'skip' 40}); 41// -> ['an']
By default, XRegExp.matchRecursive
throws an error if it scans past an unbalanced delimiter in the target string. Multiple alternative options are available for handling unbalanced delimiters.
Installation and usage
In browsers (bundle XRegExp with all of its addons):
1<script src="https://unpkg.com/xregexp/xregexp-all.js"></script>
Using npm:
1npm install xregexp
In Node.js:
1const XRegExp = require('xregexp');
Contribution guide
- Fork the repository and clone the forked version locally.
- Ensure you have the
typescript
module installed globally. - Run
npm install
. - Ensure all tests pass with
npm test
. - Add tests for new functionality or that fail from the bug not fixed.
- Implement functionality or bug fix to pass the test.
Credits
XRegExp project collaborators are:
Thanks to all contributors and others who have submitted code, provided feedback, reported bugs, and inspired new features.
XRegExp is released under the MIT License. Learn more at xregexp.com.
No vulnerabilities found.
Reason
no vulnerabilities detected
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: : LICENSE:1
Reason
dependency not pinned by hash detected -- score normalized to 9
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/liuyuchenzh/webpack-upload-plugin/build.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/liuyuchenzh/webpack-upload-plugin/build.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/build.yml:17
- Info: Third-party GitHubActions are pinned
- Info: Dockerfile dependencies are pinned
- Info: no insecure (not pinned by hash) dependency downloads found in Dockerfiles
- Info: no insecure (not pinned by hash) dependency downloads found in shell scripts
Reason
binaries present in source code
Details
- Warn: binary detected: tests/vendor/benchmark.js/nano.jar:1
Reason
branch protection is not maximal on development and all release branches
Details
- Info: 'force pushes' disabled on branch 'master'
- Info: 'allow deletion' disabled on branch 'master'
- Info: status check found to merge onto on branch 'master'
- Warn: number of required reviewers is only 0 on branch 'master'
Reason
2 commit(s) out of 30 and 1 issue activity out of 30 found in the last 90 days -- score normalized to 2
Reason
GitHub code reviews found for 4 commits out of the last 30 -- score normalized to 1
Details
- Warn: no reviews found for commit: 5fb56c105150d27d4db307d13ed3656626403ddd
- Warn: no reviews found for commit: 39e4721ed8de3917541bef2a7e4234af549d1fc3
- Warn: no reviews found for commit: 9c3cd0d518b04d89237efef7322b548b9332bf02
- Warn: no reviews found for commit: 47703c9a8ec3e5bfa7fbb2a3ae323f59ffd43060
- Warn: no reviews found for commit: e0fc4c3d23a78e98484f663cb41c89b3e5b28508
- Warn: no reviews found for commit: b8f8d5c6b95e8489b89509fd7a9f817347137430
- Warn: no reviews found for commit: 220c92abd69d3726381137a81c125037e81b171d
- Warn: no reviews found for commit: d1302bd7b9b2eb94cc9fefd61d40ed244f5c04a4
- Warn: no reviews found for commit: 66aa9b5475bc35f886935b7f9ff64b621564950d
- Warn: no reviews found for commit: 0f52a62a679580abbc0e4b7d0dc7cde43f593558
- Warn: no reviews found for commit: 82f74f51e8413c71a61d81f49f3ad7af043436fa
- Warn: no reviews found for commit: 0c1e73423a83235c55ea2dd2b9feb6fedb58549a
- Warn: no reviews found for commit: 6e1711e79af19c3e84b11b4c9b7840965a3516f0
- Warn: no reviews found for commit: bf480ecde4af0f711bfe60f07c91e41230b4a33b
- Warn: no reviews found for commit: 87aa57ee258ca3d825343012aaf393d56296718d
- Warn: no reviews found for commit: 6baec0853edd696b0ad024d110c0a9a10ec51fce
- Warn: no reviews found for commit: ca8d82a39197584da21525fc172148bff0112abe
- Warn: no reviews found for commit: 616df2362a1eda6701cee28b2a70e7d379f6ae3f
- Warn: no reviews found for commit: 06500ba825258e7a0215313d3833aea569191a93
- Warn: no reviews found for commit: c34a9260602a5f271b876f5293742b9dd1109995
- Warn: no reviews found for commit: 93f300146ed594105fae1cd6f73326bbc7e2e180
- Warn: no reviews found for commit: 618573b8a4610533587e8f804006a0c8702edb06
- Warn: no reviews found for commit: 8300a02a75bc5d0f04c4f07e7c254a20a19bb5ab
- Warn: no reviews found for commit: a7ba78aee9226f6b4129d17ccb26a74654ecbb83
- Warn: no reviews found for commit: afe4c800efaf7252f197d953d00d06d8f6bad1d7
- Warn: no reviews found for commit: 124adc0bb07a4b2dc105583214a0ae8140095603
Reason
no badge detected
Reason
non read-only tokens detected in GitHub workflows
Details
- Warn: no topLevel permission defined: .github/workflows/build.yml:1: update your workflow using https://app.stepsecurity.io/secureworkflow/liuyuchenzh/webpack-upload-plugin/build.yml/master?enable=permissions
Reason
security policy file not detected
Reason
project is not fuzzed
Reason
no update tool detected
Details
- Warn: dependabot config file not detected in source location. We recommend setting this configuration in code so it can be easily verified by others.
- Warn: renovatebot config file not detected in source location. We recommend setting this configuration in code so it can be easily verified by others.
Score
4.3
/10
Last Scanned on 2022-08-15
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to xregexp
@types/xregexp
Stub TypeScript definitions entry for xregexp, which provides its own types definitions
xregexp-quotemeta
\Q..\E (quotemeta) support for XRegExp
@gerhobbelt/xregexp
Extended regular expressions
xregexp-plugin-hanzi-cjk
add regexp-cjk plugin for xregexp, make xregexp auto match chinese/japanese hanzi.