对于Javascript中的循环正则表达式匹配

时间:2016-11-11 21:11:55

标签: javascript regex node.js loops

我很慢地学习Javascript,并且很难在正则表达式匹配上实现for循环。

我正在express.js设置中工作,index.js

中有以下内容
var express = require('express');

var router = express.Router();

// the text block against which I am running the regex

var para = "We have insisted on strict scrutiny in every context, even for so-called “benign” racial classifications, such as race-conscious university admissions policies, see Grutter v. Bollinger, 539 U.S. 306, 326 (2003), race-based preferences in government contracts, see Adarand, supra, at 226, and race-based districting intended to improve minority representation, see Shaw v. Reno, 509 U.S. 630, 650 (1993). Daniel added the following test case to the string: Crawford v. Washington, 123 U.S. 123, 123 (2016)."

// regex

var regex = /(\w+\sv.\s\w+,\s\d*\s?[\w.]*[\d,\s]*\(\d{4}\))/ig;
var regexTwo = /\w+\s/ig;

// Store the matches

var matches = para.match(regex);
var matchesTwo = para.match(regexTwo);

// the offending loop

for (var i = 0; i < matches.length; i += 1) {

    router.get('/', function(req, res) {

        res.render('index', { matches, matchesTwo, i }) });

};

module.exports = router;

我使用Jade作为HTML,我的index.jade文件如下所示:

extends layout

block content

    body
        h1 CaseSpy
        p I found the following U.S. cases in the text you provided me with:
        ul
            li #{matches}

        p I found the following other terms in the text you provided me with:
        ul
            li #{matchesTwo}

代码有效,只要它符合我想要匹配的内容。我遇到的问题是所有匹配都在同一行上捆绑,所以html输出如下所示:

输出

我在您提供给我的文本中发现了以下美国案例:

  • Grutter v.Bollinger,539 U.S. 306,326(2003),Shaw v.Reno,509 U.S. 630,650(1993),Crawford v.Washington,123 U.S. 123,123(2016)

我正在寻找的输出是:

所需输出

我在您提供给我的文本中发现了以下美国案例:

  • Grutter v.Bollinger,539 U.S. 306,326(2003)
  • Shaw v.Reno,509 U.S. 630,650(1993)
  • Crawford v.Washington,123 U.S. 123,123(2016)

我对for循环进行了无休止的修改,尝试了这种方法,但仍然遇到错误:

for (var i = 0; i < matches.length; i += 1) {
  document.body.innerHTML += matches[i] + '<br>';
}

我似乎无法解决这个问题。我知道我做了一些根本错误的事情,我只是不知道是什么。

非常感谢。

2 个答案:

答案 0 :(得分:2)

对Jade不是很熟悉,但看起来你并没有打开{matches}的包装。这可能会有所帮助:https://pugjs.org/language/iteration.html [据我所知,Jade被重命名为Pug?]

答案 1 :(得分:1)

正如Miguel所说,我相信你的Jade代码可能比使用JavaScript更多。您正尝试将所有匹配项放在单个li中,如下所示:li #{matches}

如果你尝试这样的话怎么办?

ul
each item in matches
  li= item