使用正则表达式查找搜索结果



我想在任何页面上获得搜索结果,例如,amazon或ebay。结果的形式总是像这样:

1-30 of 3.999 Results

我想要的是得到单词"results"之前的数字。为此,我将创建一个正则表达式,如:

                             (any expression) number results

如何在JavaScript中做到这一点?

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

说明:

    // bd+([.,]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»

这取决于您的编程语言,但是如果您只想要结果的总数作为字符串

/ (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,假设这是您想要的。你的问题有点含糊。

EDIT:修改为"632,090 results found for laptop".

最新更新