将用户输入字符串转换为正则表达式 [英] Converting user input string to regular expression

查看:1808
本文介绍了将用户输入字符串转换为正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用HTML和JavaScript设计一个正则表达式测试器。用户将输入一个正则表达式,一个字符串,然后通过单选按钮选择他们想要测试的函数(例如搜索,匹配,替换等),当该函数以指定的参数运行时,程序将显示结果。自然会有额外的文本框来替代额外的参数等。



我的问题是从用户处获取字符串并将其转换为正则表达式。如果我说他们不需要在他们输入的正则表达式中包含 // ,那么他们不能设置标志,比如 g i 。所以他们必须在表达式周围有 // ,但是我怎样才能把这个字符串转换成正则表达式呢?它不能是一个字面值,因为它不是一个字符串,而且我也不能将它传递给RegExp构造函数,因为它不是没有 // 的字符串。有没有其他方法可以将用户输入字符串转换为正则表达式?我需要用 // 来解析正则表达式的字符串和标志吗?然后以另一种方式构造它吗?我应该让他们输入一个字符串,然后分别输入标志吗? 使用 RegExprel =noreferrer> RegExp对象构造函数从字符串创建正则表达式:

  var re =新的RegExp(a | b,i); 
//与
相同var re = / a | b / i;


I am designing a regular expression tester in HTML and JavaScript. The user will enter a regex, a string, and choose the function they want to test with (e.g. search, match, replace, etc.) via radio button and the program will display the results when that function is run with the specified arguments. Naturally there will be extra text boxes for the extra arguments to replace and such.

My problem is getting the string from the user and turning it into a regular expression. If I say that they don't need to have //'s around the regex they enter, then they can't set flags, like g and i. So they have to have the //'s around the expression, but how can I convert that string to a regex? It can't be a literal since its a string, and I can't pass it to the RegExp constructor since its not a string without the //'s. Is there any other way to make a user input string into a regex? Will I have to parse the string and flags of the regex with the //'s then construct it another way? Should I have them enter a string, and then enter the flags separately?

解决方案

Use the RegExp object constructor to create a regular expression from a string:

var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;

这篇关于将用户输入字符串转换为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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