是否有可能在JavaScript
中执行类似preg_match
的操作PHP
?preg_match在JavaScript中?
我希望能够从字符串得到两个数字:
var text = 'price[5][68]';
成两个分离变量:
var productId = 5;
var shopId = 68;
编辑: 我也用MooTools
如果这将有助于。
是否有可能在JavaScript
中执行类似preg_match
的操作PHP
?preg_match在JavaScript中?
我希望能够从字符串得到两个数字:
var text = 'price[5][68]';
成两个分离变量:
var productId = 5;
var shopId = 68;
编辑: 我也用MooTools
如果这将有助于。
var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);
match [1] match [2]将包含您正在查找的数字。
这应该工作:
var matches = text.match(/\[(\d+)\][(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];
var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
var productId = match[1];
var shopId = match[2];
} else {
// no match
}
var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');
if(!thisRegex.test(text)){
alert('fail');
}
我发现测试表现得更为的preg_match它提供了一个布尔返回。但是你必须声明一个RegExp变种。
提示:RegExp在开始和结束时添加它自己的/所以不要传递它们。
你也可以用'/\ [(\ d +)\] \ [(\ d +)\] /。test(text)' – FlabbyRabbit 2013-05-07 15:35:19
我同意,当我看到如何重现preg_match的正则表达式测试功能时, ;) – flu 2013-10-15 17:10:23
使用RegExp类构造函数的好处是,如果需要在模式中插入一个变量,它需要一个字符串! – 2017-07-26 04:34:47
对于其他googlers; 'text.match'将返回匹配的结果。所以'var match = text.match(/ price \ [(\ d +)\] \ [(\ d +)\] /)'然后'alert(match [1]);' – Maurice 2012-09-27 14:45:28