使用regexp只获取一个匹配项

Get only one match with regexp

本文关键字:一个 regexp 获取 使用      更新时间:2023-09-26

在下面的函数中,我遍历一个包含个字符串的数组(偶发事件)。字符串描述的是从另一个网络应用程序中删除的事件(犯罪或事故),我所做的是划分和计算不同的犯罪/事故,并将它们放在一个对象中(incident_MATCHES)。

然而,一些文本字符串可能包含我搜索的几个关键词(例如"炮火"answers"电池"),但我不想要。相反,我只想计算第一个找到的单词,如果找到更多的关键词,就应该忽略它们。

这是怎么做到的?

var INCIDENT_MATCHES = {
    battery: /'w*(bråk)'w*|överfall|slagsmål|slogs|misshandel|misshandlad|'w*(tjuv)'w*/ig,
    burglaries: /snattade|snattare|snatta|inbrott|bestulen|stöld|'w*(tjuv)'w*/ig,
    robberies: /'w*(rån)'w*|personrån|'w*(ryckning)'w*|väskryckt*/ig,
    gunfire: /skottlossning|skjuten|sköt/ig,
    drugs: /narkotikabrott/ig,
    vandalism: /skadegörelse|klotter|'w*(klottra)'w*/ig,
    trafficAccidents: /(trafik|bil)olycka|(trafik|bil)olyckor|'w*(personbil)'w*|singelolycka|kollision|'w*(kollidera)'w*|påkörd|trafik|smitningsolycka/ig,
};
var j = 0,
incidentCounts = {},
incidentTypes = Object.keys(INCIDENT_MATCHES);
incidents.forEach(function(incident) {
    matchFound = false;
    incidentTypes.forEach(function(type) {
        if(typeof incidentCounts[type] === 'undefined') {
            incidentCounts[type] = 0;
        }
        var matchFound = incident.match(INCIDENT_MATCHES[type]);
        if(matchFound){
            matchFound = true;
            incidentCounts[type] += 1;
        }
    });
    j++;
});

您可以从"each"处理程序返回false以停止迭代。

    if(matchFound){
        matchFound = true;
        incidentCounts[type] += 1;
        return false;
    }

编辑—你会想要(我想)另一个测试,在外循环的末尾:

  j++; // I don't understand what that does ...
  if (matchFound) return false;

我在下面找到了这个解决方案。我所做的是:

  1. 我将第二个forEach语句替换为"every"
  2. 将"return false"放在"if(matchFound)"内
  3. 添加了"else{return true;}",以便在未找到匹配项的情况下继续循环

代码:

incidents[2].forEach(function(incident) {
    matchFound = false;
    incidentTypes.every(function(type) {
        if(typeof crimesPerType[type] === 'undefined') {
            crimesPerType[type] = 0;
    }
    var matchFound = incident.match(INCIDENT_MATCHES[type]);
    if(matchFound){
        crimesPerType[type] += 1;
        if (type == 'trafficAccidents') {
            incidents[3][j].push('traffic');
        }
        else {
            incidents[3][j].push('crime');
        }
        return false;
    }
    else {
        return true;
    }
});