2011-11-08 35 views
1

我想在任何頁面上獲得搜索結果,例如,亞馬遜或eBay。 結果總是有這樣的形式:使用正則表達式查找搜索結果

3000 1-50結果

的3.999結果

632090結果1-30找到筆記本電腦

什麼我想要的是在「結果」一詞之前得到數字。要做到這一點,我會創建一個正則表達式,如:

       (any expression) number results 

如何在JavaScript中做到這一點?

+0

「以結果搜索次數」 - 你說在你的榜樣約3999?如果您指定使用哪種語言,您將獲得更有用的答案。 – flesk

+1

你確定這些是唯一可能的兩種輸入嗎?你的預期產出呢?最後你有什麼嘗試? – FailedDev

回答

0
match = subject.match(/\b\d+([.,]\d+)*\b(?=\s+results)/i); 
if (match != null) { 
    // matched text: match[0] 
    // match start: match.index 
    // capturing group n: match[n] 
} 

說明:

// \b\d+([.,]\d+)*\b(?=\s+results) 
// 
// Options: case insensitive 
// 
// Assert position at a word boundary «\b» 
// Match a single digit 0..9 «\d+» 
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
// Match the regular expression below and capture its match into backreference number 1 «([.,]\d+)*» 
// Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
// Note: You repeated the capturing group itself. The group will capture only the last iteration. Put a capturing group around the repeated group to capture all iterations. «*» 
// Match a single character present in the list 「.,」 «[.,]» 
// Match a single digit 0..9 «\d+» 
//  Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
// Assert position at a word boundary «\b» 
// Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\s+results)» 
// Match a single character that is a 「whitespace character」 (spaces, tabs, line breaks, etc.) «\s+» 
//  Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
// Match the characters 「results」 literally «results» 
+1

關閉但是'/ \ b \ d +([。,] \ d +)?\ b(?= \ s + results)/ i'將不會匹配:''1,234,567 results'''有多於一個逗號_。問題在於:'([。,] \ d +)?',它只允許一個可選的逗號。 – ridgerunner

+0

@ridgerunner好點,我總是使用OP的樣本輸入。固定。 – FailedDev

0

這取決於你的編程語言,但如果你只想要結果的總數爲字符串

/ (\d+(?:,\d{3})*) Results/ 

將在一些語言。

爲JavaScript:

var string = "1-50 of 3000 or 1 - 16 of 3,999 Results"; 
var pattern = /.*?([^ ]+) [rR]esults.*?/ 
var match = pattern.exec(string); 
alert(match[0]); 

打印3,999,假設這是你想要的。你的問題有點含糊。

編輯:修改爲「找到筆記本電腦的632,090個結果」。

+0

謝謝,在JavaScript中:) – Noelia

+0

如果答案有效,請點擊答案左上角的箭頭圖標以接受它。 – aevanko