简体   繁体   中英

Map stringified regexp to RegExp

I want to do following:

var regex = /^\/(.*)\/?$/i;

// "/^\/(.*)\/?$/i"
var stringifiedRegex = regex.string();

// //^\/(.*)\/?$/i/
var newRegex = new RegExp(stringifiedRegex);

As you see when converting the stringified regex back to a real RegExp the regex is modified and does not match anymore the original one.

Any idea how to fix this?

Bodo

If you have to store the regex as a single string (including all flags), you can use a regex to split the regex into the parts you need to pass to new RegExp (well, that was a sentence...):

> regex = /^\/(.*)\/?$/i;
/^\/(.*)\/?$/i
> str = regex.toString()
"/^\/(.*)\/?$/i"
> m = str.match(/^[/](.*)[/]([^/]*)$/)
["/^\/(.*)\/?$/i", "^\/(.*)\/?$", "i"]
> newRegex = new RegExp(m[1], m[2])
/^\/(.*)\/?$/i

The regex matches / , then captures as much as possible, then matches the closing / and captures possible flags.

Alternatively, if you can store it across multiple fields in your database, store the source string and three booleans for the three flags separately:

> regex = /^\/(.*)\/?$/i;
/^\/(.*)\/?$/i
> regex.source
"^\/(.*)\/?$"
> regex.global
false
> regex.ignoreCase
true
> regex.multiline
false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM