Javascript 正则表达式匹配不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18657339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript regex match not working
提问by Octavian Epure
I have the following Javascript regexp:
我有以下 Javascript 正则表达式:
var regex = '/^' + name + '/';
var s ='';
s = this.innerHTML.toString().toLowerCase().match(regex);
if (s != null){
//do stuff
}
This regex does not work as expected, s
never gets set (s = null
always)
Any ideas?
这个正则表达式不能按预期工作,s
永远不会设置(s = null
总是)任何想法?
回答by Abstract Algorithm
var regex = new RegExp("^" + name);
Maybe this fixes the issue.
也许这可以解决问题。
回答by cfs
Since your pattern is dynamically generated through string concatenation, you need to create a RegExp object:
由于您的模式是通过字符串连接动态生成的,您需要创建一个 RegExp 对象:
var regex = new RegExp('^' + name + ');
回答by Andreas K?berle
You need to use RegExp object when you want to concatenate the query string. So in your case the /
are part of the query.
当您想要连接查询字符串时,您需要使用 RegExp 对象。所以在你的情况下/
是查询的一部分。
var regex = new RegExp('^' + name);
var s = '';
s = this.innerHTML.toString().toLowerCase().match(regex);
if (s != null) {
//do stuff
}
回答by lebolo
I created a jsFiddleto allow you to test various regex aspects.
我创建了一个jsFiddle来允许您测试各种正则表达式方面。
The problem is that the formatting of var regex
is incorrect. Remove the /
es:
问题是格式var regex
不正确。删除/
es:
// Test code
var name = "foobar";
//var test = "foobar at the start of a sentence";
var test = "a sentence where foobar isn't at the start";
//var regex = '/^' + name + '/'; // Wrong format
var regex = '^' + name; // correct format
var s = '';
//s = this.innerHTML.toString().toLowerCase().match(regex);
s = test.toString().toLowerCase().match(regex);
if (s != null) {
//do stuff
alert("works");
}
回答by zhon
There are two ways to create a regular expression:
创建正则表达式有两种方法:
1) Using the literal form
1) 使用字面形式
var re = /\w+/;
2) Using object creation form
2) 使用对象创建形式
var re = new RegExp("\w+");
Typically you will want the literal form. In your case were you are creating it from a string you must use the object creation form.
通常,您需要文字形式。在您的情况下,您是从字符串创建它的,您必须使用对象创建表单。
var re = new RegExp("^" + name);
回答by Jules G.M.
Just removing the slashes works.
只需删除斜线即可。
pattern = function(name){"^"+name;}
(name + "whatever").match(pattern(name)); // not null
("whatEver..NotName").match(pattern(name)); // null