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

时间:2011-11-08 12:03:03

标签: javascript regex

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

1-50 of 3000 Results

3.999结果中的1-30

632,090搜索到笔记本电脑的结果

我想要的是在“结果”之前得到数字。为此,我将创建一个正则表达式,如:

                             (any expression) number results

如何在JavaScript中执行此操作?

2 个答案:

答案 0 :(得分: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搜索结果”。

答案 1 :(得分: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»
相关问题