2010-07-20 42 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