How to pass a regular expression as a function parameter

Asked
Active3 hr before
Viewed126 times

9 Answers

parameterregularexpressionfunction
90%

or pass the expression directly:, Stack Overflow Public questions & answers , GitLab launches Collective on Stack Overflow ,Either format your expression properly:

Either format your expression properly:

function doit(expression) {
   var regex = new RegExp(expression, 'g');
   alert(regex.test('mename@memail.com'));
}

doit("^\\w+([-+.\\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
// no / here, escape \
load more v
88%

How can I pass a regular expression constant as an argument to a function, so that the function can receive the argument as a regular expression instead of a truth value?, You can use quotes to pass regular expressions as arguments to functions: mysub("hi", "howdy", text, 1). – Satō Katsura Jul 19 '17 at 15:20 ,In other word, before a regular expression constant is passed into a function, how can I prevent it from being evaluated as a string matching expression, and ensure it being treated as what it is?,How can regular expression constants be passed to those builtin functions (e.g. match, split, sub) as regular expressions, without being evaluated as a string matching expression?

You should use quotes to pass values to function variables.

mysub("hi", "howdy", text, 1)
load more v
72%

Either format your expression properly:,Because when creating a regex with new RegExp(), you don't use the delimiters. Remove the / from before and after the string.,Alternatively, pass the regex itself by removing the quotes before and after, and leave out the new RegExp() call.,The slashes (/) are not part of the expression, they denote a regex literal. If you use a string containing the expression, you have to omit them and escape every backslash since the backslash is the escape character in strings as well.

Why this returns false instead of true.

function doit(expression) {

   var regex = new RegExp(expression, 'g');

   alert(regex.test('[email protected]'));
}

doit("/^w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*/");​
load more v
65%

Escape Characters and Caveats,List of Regex Functions,Note that the backslash character needs to be escaped (i.e. \\ becomes \). For more information, see Escape Characters and Caveats (in this topic).,Date & Time Functions

\d: decimal digit (0-9).

\
d
load more v
75%

import re
   >>>
   m = re.search('(?<=abc)def', 'abcdef') >>>
   m.group(0)
'def'
40%

I want my regex to take value inside the before variable directly to regex. How can i do it,str.replace(/(?=${before})(\w+)/,after); Here the before (string literals) is not working. I want my regex to take value inside the before variable directly to regex. How can i do it,I tired changing my code still the variable before is somehow is not reading it value.,Anytime you use a special meta character like \s or \w or \b, you must add the extra backslash for the string version of the regular expression to work with RegExp.

Your code so far

function myReplace(str, before, after) {

 let regex=`/(?=<before>)(\w+)/`;
 let replacedStr = str.replace(regex,after);
 
 return replacedStr;
// let re = new RegExp(regex,"g");

 //return str.replace(/(?=${before})(\w+)/,after);
 
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));

load more v
22%

Executes a search for a match in its string parameter.,Tests for a match in its string parameter.,The following three expressions create the same regular expression object:,Note that the order of the patterns in the regular expression matters.

let re = /ab+c/i; // literal notation
let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument
let re = new RegExp(/ab+c/, 'i') // constructor with regular expression literal as first argument (Starting with ECMAScript 6)
load more v
60%

in a string passed to the repl argument of re.sub(),It is important to note that most regular expression operations are available as module-level functions and methods on compiled regular expressions. The functions are shortcuts that don’t require you to compile a regex object first, but miss some fine-tuning parameters.,This means that the two following regular expression objects that match a decimal number are functionally equal:,Compiled regular expression objects support the following methods and attributes:

>>>
import re
   >>>
   m = re.search('(?<=abc)def', 'abcdef') >>>
   m.group(0)
'def'
load more v
48%

Indicates whether the regular expression finds a match in the input string.,Indicates whether the specified regular expression finds a match in the specified input string.,Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.,Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.

public:
   bool IsMatch(System::String ^ input);
public bool IsMatch(string input);
member this.IsMatch: string - > bool
Public Function IsMatch(input As String) As Boolean

The following example illustrates the use of the IsMatch(String) method to determine whether a string is a valid part number. The regular expression assumes that the part number has a specific format that consists of three sets of characters separated by hyphens. The first set, which contains four characters, must consist of an alphanumeric character followed by two numeric characters followed by an alphanumeric character. The second set, which consists of three characters, must be numeric. The third set, which consists of four characters, must have three numeric characters followed by an alphanumeric character.

using System;
using System.Text.RegularExpressions;

public class Example {
   public static void Main() {
      string[] partNumbers = {
         "1298-673-4192",
         "A08Z-931-468A",
         "_A90-123-129X",
         "12345-KKA-1230",
         "0919-2893-1256"
      };
      Regex rgx = new Regex(@ "^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$");
      foreach(string partNumber in partNumbers)
      Console.WriteLine("{0} {1} a valid part number.",
         partNumber,
         rgx.IsMatch(partNumber) ? "is" : "is not");
   }
}
// The example displays the following output:
//       1298-673-4192 is a valid part number.
//       A08Z-931-468A is a valid part number.
//       _A90-123-129X is not a valid part number.
//       12345-KKA-1230 is not a valid part number.
//       0919-2893-1256 is not a valid part number.
Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim partNumbers() As String = {
   "1298-673-4192",
   "A08Z-931-468A",
   _ "_A90-123-129X",
   "12345-KKA-1230",
   _ "0919-2893-1256"
}
Dim rgx As New Regex("^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$")
For Each partNumber As String In partNumbers
Console.WriteLine("{0} {1} a valid part number.", _ partNumber, _ IIF(rgx.IsMatch(partNumber), "is", "is not"))
Next
End Sub
End Module
   ' The example displays the following output:
'       1298-673-4192 is a valid part number.
'       A08Z-931-468A is a valid part number.
'       _A90-123-129X is not a valid part number.
'       12345-KKA-1230 is not a valid part number.
'       0919-2893-1256 is not a valid part number.

The regular expression pattern is:

^ [a - zA - Z0 - 9]\ d {
   2
} [a - zA - Z0 - 9](-\d {
   3
}) {
   2
} [A - Za - z0 - 9] $
load more v

Other "parameter-regular" queries related to "How to pass a regular expression as a function parameter"