Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a regular expression to a String literal and back again?

Tags:

People also ask

What does \\ mean in regular expression?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.

What is the regular expression for string?

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .

Why do raw strings often appear in Regex objects in Python?

Why are raw strings often used when creating Regex objects? Raw strings are used so that backslashes do not have to be escaped.

How do you match a regular expression?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .


How can I:

  1. Convert a JavaScript RegExp with flags to a String literal (think JSON),
  2. And convert that literal back to a regex?

For example with the String "the weather is nice today":

var myRe = new RegExp("weather","gi");
var myReToString = myRe.toString(); // myReToString is now "/weather/gi"

var myReCopy = /* How to get this copy only from myReToString ? */

To modify the original RegExp properties see torazaburo's answer.