将RegExp转换为String然后再返回RegExp [英] converting RegExp to String then back to RegExp

查看:175
本文介绍了将RegExp转换为String然后再返回RegExp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个RegExp regex = / asd /

So I have a RegExp regex = /asd/

我将它存储为关键字在我的key-val商店系统中。

I am storing it as a as a key in my key-val store system.

所以我说 str = String(正则表达式)返回/ asd /

现在我需要将该字符串转换回RegExp。

Now I need to convert that string back to a RegExp.

所以我尝试: RegExp(str)我看到 / \ / asd\ //

这不是我想要的。它与 / asd /

this is not what I want. It is not the same as /asd/

不一样我应该先删除字符串中的第一个和最后一个字符将它转换为正则表达式?在这种情况下,这会让我获得理想的结果,但如果RegExp具有 / i / g

Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g

有更好的方法吗?

推荐答案

如果您不需要存储修饰符,可以使用 Regexp#source 获取字符串值,然后使用 RegExp 构造函数。

If you don't need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.

var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");






如果确实需要存储修饰符,请使用正则表达式解析正则表达式:


If you do need to store the modifiers, use a regex to parse the regex:

var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = /\/(.*)\/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);

即使模式具有 / 在其中,因为。* 是贪婪的,并将前进到字符串中的最后一个 /

This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.

如果需要考虑性能,请使用 String#lastIndexOf

If performance is a concern, use normal string manipulation using String#lastIndexOf:

var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));

这篇关于将RegExp转换为String然后再返回RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆