Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

javascript - 将用户输入字符串转换为正则表达式(Converting user input string to regular expression)

I am designing a regular expression tester in HTML and JavaScript.(我正在设计HTML和JavaScript中的正则表达式测试器。)

The user will enter a regex, a string, and choose the function they want to test with (eg 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 .(如果我说他们不需要在输入的正则表达式周围加上// ,那么他们就不能设置标志,例如gi 。) 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.(它不能是文字,因为它是一个字符串,我不能将其传递给RegExp构造函数,因为它不是没有//的字符串。) 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?(我应该让他们输入一个字符串,然后分别输入标志吗?)   ask by Gordon Gustafson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the RegExp object constructor to create a regular expression from a string:(使用RegExp对象构造函数从字符串创建正则表达式:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...