Javascript提取不包含列表中任何单词的句子

时间:2017-01-17 17:10:12

标签: javascript arrays algorithm

我目前正在尝试从不包含单词列表中任何单词的列表中提取句子。

列表包含字母和数字,大写和小写。

我设法提取了句子列表中包含的单词但由于某种原因我无法从句子列表中提取不包含单词列表中任何单词的句子。

以下是输入的一些Pseaudo代码与预期输出相反:

//input
var list1 = ["sentence with word1", "sentence with word2", "sentence without 3"];
var list2 = ["word1", "word2", "word3"];


//To fill out
var list1ContainedWords = [];
var list1DidntContainWords = [];

var extract = function (list1, list2) {

}

//Expected output
list1ContainedWords = ["word1", "word2"];
list1DidntContainWords = ["sentence without 3"];

2 个答案:

答案 0 :(得分:3)

使用第二个数组生成正则表达式,并使用RegExp#test方法检查模式匹配。

body {
    background:#a5c8f3 !important;
    font-family: 'Raleway', sans-serif;
    padding-top: 50px;
    overflow: hidden;
}
.scrol_sctn { 
    margin:0; 
    padding:0;
    overflow-y: auto;
    overflow-x: hidden;
}

var extract = function(list1, list2) {
  // object for storing the result, do it as you want
  var res = {
    contains : [],
    notContains : []
  };

  // generate regex using the second list strings
  // in a way which matches any of the string
  var regex = new RegExp(list2.map(function(v) {
    // escape any of the symbol which has special meaning in regex
    // although use word boundary in case you want exact match
    // word boundary can be either use here or wrap by a gruop and use it commonly
    return '\\b' + v.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + '\\b';
    // join them using pipe symbol(or)
  }).join('|'));

  // or alternate with word boundary with a group
  // '\\b(' + list2.map(....).join('|') + ')\\b'
  // or with non-capturing group
  // '\\b(?:' + list2.map(....).join('|') + ')\\b'

  // iterate over the first list
  list1.forEach(function(v) {
    // check pattern is matching, if matching push into contains property
    if (regex.test(v))
      res.contains.push(v);
    // if not push into notContains property
    else
      res.notContains.push(v);
  })

  // return the result object
  return res;
}
请参阅:Converting user input string to regular expression

答案 1 :(得分:0)

这样的事情可能是一个很好的解决方案:

getSupportFragmentManager().beginTransaction().add(R.id.the_view_into_which_the_fragment_goes, the_fragment, "tag").commit();'

基本上,循环遍历两个数组,只是检查单词是否在句子中并跟踪它。