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?
If using the RegExp constructor with a string literal, remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level. /a\*b/ and new RegExp("a\\*b") create the same expression, which searches for "a" followed by a literal "*" ...
format(is_valid_regex(user_input, escape=False))) print("If you do use re. escape, the input is valid: {}.". format(is_valid_regex(user_input, escape=True))) if is_valid_regex(user_input, escape=False): regex = re. compile(user_input) print("\nRegex compiled as '{}' with type {}.".
A regular expression (regex) defines a search pattern for strings. The search pattern can be anything from a simple character, a fixed string or a complex expression containing special characters describing the pattern.
The () will allow you to read exactly which characters were matched. Parenthesis are also useful for OR'ing two expressions with the bar | character. For example, (a-z|0-9) will match one character -- any of the lowercase alpha or digit.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With