Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape a variable within a Regular Expression

I am trying to take the value of an input text field and use it within a regular expression. Here's what I have to match the start of a line.

regex = new RegExp('^' + inputValue, 'i')

It works fine for regular strings that start have alphanumeric characters, but I am using this for dollar amounts as well. When the input field starts with a '$' (dollar sign) i get varying results.

How can I escape the variable above to be viewed as a simple string? I've tried this, but no luck:

regex = new RegExp('^[' + inputValue + ']', 'i')
like image 433
CoryDorning Avatar asked Mar 08 '12 17:03

CoryDorning


People also ask

Can you use variables in regular expressions?

In a regular expression, variable values are created by parenthetical statements.

How do you use a variable inside a regex pattern?

Solution 1. let year = 'II'; let sem = 'I'; let regex = new RegExp(`${year} B. Tech ${sem} Sem`, "g"); You need to pass the options to the RegExp constructor, and remove the regex literal delimiters from your string.

What does escape do in regex?

Escape converts a string so that the regular expression engine will interpret any metacharacters that it may contain as character literals.


1 Answers

Probably one of the better implementations I've seen

http://phpjs.org/functions/preg_quote:491

Copied below for posterity

function preg_quote (str, delimiter) {
    // Quote regular expression characters plus an optional character  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/preg_quote    // +   original by: booeyOH
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // *     example 1: preg_quote("$40");
    // *     returns 1: '\$40'
    // *     example 2: preg_quote("*RRRING* Hello?");
    // *     returns 2: '\*RRRING\* Hello\?'
    // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");    // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
    return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}
like image 134
Peter Bailey Avatar answered Sep 21 '22 11:09

Peter Bailey