【问题标题】:How to find certain words in string?如何在字符串中找到某些单词?
【发布时间】:2016-09-13 09:48:01
【问题描述】:

我有一个字符串数组,每个字符串都包含一个关键字和一个数字(数值不同,只有关键字是常数),我想知道如何获取单词和数字.. .看下面的例子:

var keyWords = ["data","action","type"];

var stringArray = ["set data4 to custom value '1'",
                   "set data110 to custom value '2'",
                   "overwrite value of action1023 with new value",
                   "set type23 to custom value '10'",
                   "overwrite value of action13 with text",
                   "set type48 to custom value '7'"]

响应应该是这样的:

var response = ["data4","data110","action13","type23","action1023","type48"];

这是我设法做到的:

  var response = [];
  for(var j=0; j<keyWords.length; j++) {
    for(var i=0; i<stringArray.length; i++) {
      if(stringArray[i].indexOf(keyWords[j]) !== -1) {
        response.push(keyWords[j]);
      }
    }
  }

但它只返回确切的关键词,没有数字..

response = [data, data, action, action, type, type]

【问题讨论】:

  • 我只是设法从数组中获取关键字,但没有数字...
  • @Typo 我会尝试使用正则表达式来实现解决方案,谢谢!

标签: javascript arrays regex string search


【解决方案1】:

如果您想采用正则表达式方法,

这个例子可能就是你要找的:

var found = [],
    result;   

for(var i in stringArray){
   result = stringArray[i].match(/(data|action|value|type)(\d+)/);
   found.push(result);
}

"found" 数组中,您应该得到一个项目列表,每个项目都包含以下数据:

  1. 原始关键字匹配(带数字的关键字字符串)
  2. 关键字字符串部分(不含数字)
  3. 仅数字(从关键字中提取)

示例输出:

[["data4", "data", "4"], ["data110", "data", "110"], ["action1023", "action", "1023"], ["type23", "type", "23"], ["action13", "action", "13"], ["type48", "type", "48"]]

希望对你有所帮助。

【讨论】:

  • 您应该使用\d+ 而不是\d* 作为数字以避免匹配关键字的其他出现(例如“覆盖...的”)
  • 您可能还想更新输出 :) ["value", "value", ""] 不再是其中的一部分
【解决方案2】:

这段代码完成了这项工作

var keyWords = ["data","action","value","type"];

var stringArray = ["set data4 to custom value '1'",
               "set data110 to custom value '2'",
               "overwrite value of action1023 with new value",
               "set type23 to custom value '10'",
               "overwrite value of action13 with text",
               "set type48 to custom value '7'"]

var response = [];

for(var i = 0; i < stringArray.length; ++i){
    for(var j = 0; j < keyWords.length; ++j){
        if((index = stringArray[i].indexOf(keyWords[j])) !== -1){
            splittedStr = stringArray[i].substring(index,         stringArray[i].length).split(' ', 1);
            response.push(splittedStr[0]);
        }
    }
}
console.log(response);

【讨论】:

    【解决方案3】:

    非常直接的方法:

    var keyWords = ["data","action","value","type"];
    
    var stringArray = ["set data4 to custom value '1'",
                       "set data110 to custom value '2'",
                       "overwrite value of action1023 with new value",
                       "set type23 to custom value '10'",
                       "overwrite value of action13 with text",
                       "set type48 to custom value '7'"]
    
    function f(keyWords, stringArray){
    	let output = []
    	
    	stringArray.forEach((sentence) => {
    		var words = sentence.split(' ')
    	
    		words.forEach((word) => {
    			keyWords.forEach((keyword) => {			
    				if(word.indexOf(keyword) > -1 ) {
    					output.push(word)
    				}				
    			})
    		})
    	})
    		
    	return output
    }
    
    console.log(f(keyWords, stringArray))

    【讨论】:

    • 不返回包含“action”的单词
    • 已修复,我认为只需要第一个匹配项。
    【解决方案4】:

    ...一种更通用和功能更强大的方法...

    var
        keyList       = ["data", "action", "value", "type"],
    
        sentenceList  = [
            "set data4 to custom value '1'",
            "set data110 to custom value '2'",
            "overwrite value of action1023 with new value",
            "set type23 to custom value '10'",
            "overwrite value of action13 with text",
            "set type48 to custom value '7'"
        ],
    
        wordList = sentenceList.reduce(function collectSpecificWords (collector, sentence) {
            var
                matchList = sentence.split(/\s+/).filter(function (word) {
    
                    return collector.regXWord.test(word);
                });
    
            collector.wordList = collector.wordList.concat(matchList);
    
            return collector;
    
        }, {
    
          //regXWord: RegExp("^("+ keyList.join("|") + ")[0-9]+$"),
            regXWord: RegExp("^("+ keyList.join("|") + ")[0-9]*$"),
            wordList: []
    
        }).wordList;
    
    
    console.log("wordList : ", wordList);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2021-06-22
      • 2022-01-24
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      相关资源
      最近更新 更多