2011-09-16 13 views
0

如何構建一個正則表達式搜索一個較大的子串,看起來像:Javascript正則表達式如何?

"x bed" OR "x or y bed" 

在這兩種情況下,我需要訪問這兩個變量x和y,這兩者都是整數。

任何幫助表示讚賞....

回答

1

使用JavaScript -

var subject = "1 bed,2 or 3 bed" 
var myregexp = /(\d+) bed|(\d+) or (\d+) bed/img; 
var match = myregexp.exec(subject); 
while (match != null) { 
    if (match[1]) { 
     alert("Found 'x bed', x is '" + match[1] + "'");  
    } 
    else { 
     alert("Found 'x or y bed', x is '" + match[2] + "', y is '" + match[3] + "'"); 
    }  

    match = myregexp.exec(subject); 
} 

演示 - http://jsfiddle.net/ipr101/WGUEH/

+0

非常好,謝謝! –

3
(?:\d+ or)?\d+ bed 

捕捉 「X牀」,並添加一個可選的 「X或」

+2

您需要捕獲組來包裝他要尋找的變量。 '(?:(\ d +)\ S +或\ S +)?(\ d +)\ S + bed'。 – Benjam

1

試試這個

(\d+)\s+or\s+(\d+)\s+bed|(\d+)\s+bed 

H個!

+0

@Galen - 你發佈的正則表達式不適合我。當我在虛擬輸入上運行它時,我什麼也得不到 - 「10或12張牀,10張牀,然後是15或16張牀」 – rebnoob

1

我假設你想這種類型的輸出:

"23 bed"   => "23" 
"32 or 45 bed"  => "32", "45" 
"4"    => no matches 
"99 or bed"  => no matches 
"or bed"   => no matches 

如果這是你想要什麼的正確解釋,那麼你可以使用這個表達式:

/(\d+)\s+bed|(\d+)\s+or\s+(\d+)\s+bed/

這是代碼的輪廓用它

var str = "32 or 45 bed"; 
var matches = str.match(/(\d+)\s+bed|(\d+)\s+or\s+(\d+)\s+bed/); 
if (matches) { 
    alert(matches[1]);  // first numeric match 
    alert(matches[3]);  // second numeric match (null if not present) 
} 

你可以看到一個試驗檯的位置:

http://jsfiddle.net/jfriend00/9n5XK/

通過解釋,正則表達式是兩部分。的第一塊是:

(\d+)\s+bed 

any sequence of digits that are captured 
followed by any amount of whitespace 
followed by "bed" 

第二部分是這樣的:

(\d+)\s+or\s+(\d+)\s+bed/ 

any sequence of digits that are captured 
followed by any amount of whitespace 
followed by "or" 
followed by any mount of whitespace 
followed by any sequence of digits that are captured 
followed by any amount of whitespace 
followed by "bed" 

正則表達式設置,以便它將所述第一片的正則表達式或所述第二片的正則表達式的匹配。

因此,捕獲的棋子將在第1,2和3槽的匹配數組中。正則表達式設置的方式,第一個匹配將位於第1或第2槽中(無論哪個不爲空),以及第二匹配(如果存在)將在插槽3

我不要求這是最短的可能的正則表達式,可以匹配這一點,但它是簡單易懂。