2017-03-01 53 views
-1

我想匹配包含強制性單詞或重複單詞序列的字符串。我甚至不知道我是否可以用Regexp來做到這一點。正則表達式匹配強制性單詞和單詞序列

例串

No depending be convinced in unfeeling he. 
Excellence she unaffected and too sentiments her. 
Rooms he doors there ye aware in by shall. 
Education remainder in so cordially. 
His remainder and own dejection daughters sportsmen. 
Is easy took he shed to kind. 

強制性的話

Rooms (1x) 
Excellence (2x) 
Education (1x) 
House (1x) 

應該返回類似

Success: false 

Rooms: 1 
Excellence: 1 
Education: 1 
House: 0 

感謝支持

回答

1

你可以做這樣的事情:

var requiredWords = { 
    Rooms: 1, 
    Excellence: 2, 
    Education: 1, 
    House: 1, 
}; 

var success = true; 
for(var word in requiredWords){ 
    var requiredAmount = requiredWords[word]; 

    //create and check against regex 
    var regex = new RegExp(word, 'g'); 
    var count = (yourString.match(regex) || []).length; 

    //if it doesn't occur often enough, the string is not ok 
    if(count < requiredAmount){ 
    success = false; 
    } 
} 

alert(success); 

您創建一個對象,其中包含所需的所有字,然後遍歷它們並檢查它們是否經常發生。如果沒有一個單詞失敗,則字符串是OK。

jsFiddle

+0

嘿感謝,這正是我一直在現在的編碼!謝謝你的時間 – bln

+0

我可以問你smtg其他嗎? 如果我有2個強制性的「串」像 - 我的名字 - 命名 和句子,如「我的名字是約翰 我怎麼能相信只匹配「我的名字」,而不是「名稱」中這個案例? – bln

1

該解決方案使用String.prototype.match()Array.prototype.reduce()功能:

function checkMandatoryWords(str, wordSet) { 
 
    var result = Object.keys(wordSet).reduce(function (r, k) { 
 
     var m = str.match(new RegExp('\\b' + k + '\\b', 'g')); 
 
     r[k] = m? m.length : 0; // writing the number of occurrences 
 
     if (m && m.length !== wordSet[k]) r.Success = false; 
 

 
     return r; 
 
    }, {Success: true}); 
 

 
    return result; 
 
} 
 

 
var str = "No depending be convinced in unfeeling he. \ 
 
Excellence she unaffected and too sentiments her.\ 
 
    Rooms he doors there ye aware in by shall.\ 
 
    Education remainder in so cordially.\ 
 
    His remainder and own dejection daughters sportsmen.\ 
 
    Is easy took he shed to kind. ", 
 

 
    wordSet = {Rooms: 1, Excellence: 2, Education: 1, House: 1}; 
 

 
console.log(checkMandatoryWords(str, wordSet));

相關問題