Искать строку и возвращать найденные слова - PullRequest
0 голосов
/ 03 октября 2018

Я хочу найти в строке слова, найденные в массиве книг, и вернуть найденные слова.Я удалил специальные символы.Но я не могу понять, как искать строку.Поиск возвращает -1

       <script>
var books = ['Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua', 'Judges'
, 'Ruth', 'Samuel', 'Samuel', 'Kings', 'Kings', 'Chronicles', 'Chronicles', 'Ezra', 'Nehemiah',
'Esther', 'Job', 'Psalms', 'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', 'Jeremiah',
'Lamentations', 'Ezekiel', 'Daniel', 'Hosea', 'Joel', 'Amos', 'Obadiah', 'Jonah', 'Micah',
'Nahum', 'Habakkuk', 'Zephaniah', 'Haggai', 'Zechariah', 'Malachi', 'Matthew',
'Mark', 'Luke', 'John', 'Acts', 'Romans', 'Corinthians', 'Galatians', 'Ephesians', 'Philippians',
'Colossians', 'Thessalonians', 'Timothy', 'Timothy', 'Titus', 'Philemon', 'Hebrews', 'James',
'Peter', 'Peter', 'John', 'Jude', 'Revelation'];



var puzzle = 'Can you find the names of 25 books of the Bible in this paragraph? This is a most remarkable puzzle.\
 Someone found it in the seat pocket on a flight from Los Angeles to Honolulu, keeping himself occupied for hours.\
  One man from Illinois worked on this while fishing from his john boat. Roy Clark studied it while playing his banjo. \
  Elaine Victs mentioned it in her column once. One woman judges the job to be so involving, she brews a cup of tea to \
  help calm her nerves. There will be some names that are really easy to spot that’s a fact. Some people will soon find \
  themselves in a jam, especially since the book names are not necessarily capitalized. The truth is, from answers\
  we get, we are forced to admit it usually takes a minister or scholar to see some of them at the worst. \
  Something in our genes is responsible for the difficulty we have. Those able to find all of them will hear \
  great lamentations from those who have to be shown. One revelation may help, books like! Timothy and Samuel \
  may occur without their numbers. And punctuation or spaces in the middle are normal. \
  A chipper attitude will help you compete. Remember, there are 25 books of the Bible lurking \
 somewhere in this paragraph. Greater love hath no man than this, that a man lay down his life for his friends. John 15:13.';
// Remove punctuation and spaces and set to lowercase

var matcher = /[a-z]+/gi;
var matches = puzzle.match(matcher);
var result = matches.join('');
var results = result.toLowerCase();
books = books.map(function (e) {
    return e.toLowerCase();
  });

//Search results for books and return those found
var i;
for (i = 0; i < books.length; i++) {
  var found =  puzzle.search(books)
  console.log(found);
}
      </script>

Ответы [ 3 ]

0 голосов
/ 03 октября 2018

Поскольку это небольшая головоломка, вот алгоритм, как ее решить:

  1. В puzzle строке вы должны удалить все символы, кроме букв.
  2. Вpuzzle строка перемещает все буквы в нижний регистр.
  3. Перемещает все книги в массиве books также в нижний регистр.
  4. Для каждого элемента из массива books следует использовать puzzle.search(book).Если результат неотрицательный, эта книга в тексте.
  5. Соберите все книги, у которых был неотрицательный результат, в новый массив.

Последние два шага можно выполнить с помощью for цикл или использование reduce метода для books массива.Ниже приведен пример, как это можно сделать:

puzzle = puzzle.replace(/\W/g,'').toLowerCase();

let result = [];

for(let i = 0; i < books.length; i++) {
  const index = puzzle.search(books[i].toLowerCase());
  if(index >= 0 && result.indexOf(books[i]) == -1) {
    result.push(books[i]);
  }
}

console.log(result);
console.log(result.length);
0 голосов
/ 05 октября 2018
let reg = new RegExp('(' + books.join('|') + ')', 'gi');
let answer = puzzle.replace(/[^\w]/g,'').match(reg);
console.log(answer);

Если вы используете этот код сразу после объявления puzzle, он должен работать.

Вы можете создавать циклы и карты и все такое, либо использовать регулярное выражение для получения ответа.

Я проверял это только в окне инструментов разработчика Chrome, но оно должно работать везде, где это возможно.он запускается.

Первая строка создает объект регулярного выражения, который не учитывает регистр и будет искать всю строку, в которой он используется.Если бы вы сделали console.log(reg), это выглядело бы примерно так /(book1|book2|book3|...)/gi.

Вторая строка принимает puzzle, удаляет все несловарные символы (puzzle.replace(/[^\w]/g,'')), затем сопоставляет регулярное выражение, которое былопостроено на линии 1 (.match(reg)).

0 голосов
/ 03 октября 2018

Попробуйте

var matcher = books.join('|');
var matches = puzzle.match(matcher);
var result = matches.join(' ');
console.log(result);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...