Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Character set from string array #292

Closed
miloshavlicek opened this issue Apr 16, 2020 · 2 comments
Closed

Feature request: Character set from string array #292

miloshavlicek opened this issue Apr 16, 2020 · 2 comments

Comments

@miloshavlicek
Copy link

miloshavlicek commented Apr 16, 2020

Feature request (for discussion):
It would be useful to be able to create a new character set from a string array of allowed chars.

At this time I have my own static function that escapes and joins chars from string array, however, I think it can be useful also for others.

Example implementation:

const matchingChars = ['a','e','i','o','u', '+'];
const result = [];
const re = XRegExp(`${XRegExp.charsetFromArray(matchingChars)}+`); // expected translation: [aeiou\+]+
while (match = XRegExp.exec('heeeja+aola', re)) {
    result.push(match);
}
// expected output: ['eee', 'a+ao', 'a']
@slevithan
Copy link
Owner

How about:

const chars = 'aeiou+'; // or: ['a','e','i','o','u','+'].join('');
const re = XRegExp('[' + XRegExp.escape(chars) + ']+');
const result = XRegExp.match('heeeja+aola', re, 'all'); // ['eee','a+ao','a']

If it wasn’t for the bug described in #192 (where interpolation isn’t currently allowed inside character classes), you could replace the second line with const re = XRegExp.tag()`[${chars}]+`;.

@mathiasbynens
Copy link
Collaborator

Note that for usage with plain JS regular expressions (i.e. without XRegExp), regenerate solves this problem. Given a set of characters, it produces a valid & ASCII-safe JS regular expression pattern that matches only those characters.

regenerate('a','e','i','o','u', '+').toString();
// --> '[\\+aeiou]'

https://repl.it/repls/BackThirstySoftwareengineer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants