像这样的模式需要正则表达式

时间:2014-05-26 10:23:31

标签: javascript regex

我想在Javascript(不是jQuery)中使用正则表达式解析字符串。

方案是数据位于div元素中,每个div都包含此类HTML。没有评论,或者具有正确格式的数值,如1,836条评论

User Name 1 | From
Accountant, 5 years of experience
1,836 comments

User Name 3 | From
Accountant, 5 years of experience

User Name 2 | From
Accountant, 5 years of experience
836 comments

我只需要上面评论的正则表达式。

1 个答案:

答案 0 :(得分:0)

RegEx101:

[0-9,]+    (?# match 1+ 0-9 or , characters)
(?=        (?# start lookahead)
  \s+      (?# match 1+ whitespace characters)
  comment  (?# match comment literally)
  s?       (?# optionally match s literally)
)          (?# end lookahead)

JSFiddle:

// Set up variables
var elements = document.getElementsByClassName('data'),
    length = elements.length,
    regex = /[0-9,]+(?=\s+comments?)/;

// Loop elements
for(var i = 0; i < length; i++) {
    var html = elements[i].innerHTML,
        comments = 0;

    // Match against the expression
    var matches = html.match(regex);
    if(matches && matches.length) {
        comments = matches[0].replace(/,/g, ''); // Replace commas
        comments = parseInt(comments);           // String to integer (optional)
    }

    console.log(comments); // 1836, 0, 836
}