转义正则表达式中的变量 [英] 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')
推荐答案
可能是我更好的实施之一已见过
Probably one of the better implementations I've seen
http://phpjs.org / functions / preg_quote:491
下面为后代复制
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'), '\\$&');
}
这篇关于转义正则表达式中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!