2010-07-20 43 views
55

是否有可能在JavaScript中执行类似preg_match的操作PHPpreg_match在JavaScript中?

我希望能够从字符串得到两个数字:

var text = 'price[5][68]'; 

成两个分离变量:

var productId = 5; 
var shopId = 68; 

编辑: 我也用MooTools如果这将有助于。

回答

85

JavaScript有一个RegExp对象,它可以做你想做的事。 String对象有一个match()函数可以帮助你。

var matches = text.match(/price\[(\d+)\]\[(\d+)\]/); 
+26

对于其他googlers; 'text.match'将返回匹配的结果。所以'var match = text.match(/ price \ [(\ d +)\] \ [(\ d +)\] /)'然后'alert(match [1]);' – Maurice 2012-09-27 14:45:28

26
var text = 'price[5][68]'; 
var regex = /price\[(\d+)\]\[(\d+)\]/gi; 
match = regex.exec(text); 

match [1] match [2]将包含您正在查找的数字。

5

这应该工作:

var matches = text.match(/\[(\d+)\][(\d+)\]/); 
var productId = matches[1]; 
var shopId = matches[2]; 
4
var myregexp = /\[(\d+)\]\[(\d+)\]/; 
var match = myregexp.exec(text); 
if (match != null) { 
    var productId = match[1]; 
    var shopId = match[2]; 
} else { 
    // no match 
} 
13
var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]'); 

if(!thisRegex.test(text)){ 
    alert('fail'); 
} 

我发现测试表现得更为的preg_match它提供了一个布尔返回。但是你必须声明一个RegExp变种。

提示:RegExp在开始和结束时添加它自己的/所以不要传递它们。

+6

你也可以用'/\ [(\ d +)\] \ [(\ d +)\] /。test(text)' – FlabbyRabbit 2013-05-07 15:35:19

+0

我同意,当我看到如何重现preg_match的正则表达式测试功能时, ;) – flu 2013-10-15 17:10:23

+0

使用RegExp类构造函数的好处是,如果需要在模式中插入一个变量,它需要一个字符串! – 2017-07-26 04:34:47