Как извлечь слова и фразы из строки, используя массив в Javascript (JS)? - PullRequest
2 голосов
/ 29 июня 2010

Я посмотрел несколько примеров использования регулярных выражений в JS, но я не могу найти правильный синтаксис для того, что мне нужно.В основном у меня есть массив слов:

commonWords=["she", "he", "him", "liked", "i", "a", "an", "are"]

и строка:

'She met him where he liked to eat "the best" cheese pizza.'

В основном я хочу использовать non-alphas и мой массив commonWords в качестве разделителей для выделения фраз.Выше приведено что-то вроде этого:

'met, where, to eat, the best, cheese pizza'

Ответы [ 3 ]

2 голосов
/ 29 июня 2010

Вы ищете что-то подобное:

var commonWords=["she", "he", "him", "liked", "i", "a", "an", "are"];
var regstr = "\\b(" + commonWords.join("|") + ")\\b";
//regex is \b(she|he|him|liked|i|a|an|are)\b
var regex = new RegExp(regstr, "ig");
var str = 'She met him where he liked to eat "the best" cheese pizza.';
console.log(str.replace(regex, ""));

вывод

 met where to eat "the best" cheese pizza.

split версия:

var commonWords=["she", "he", "him", "liked", "i", "a", "an", "are"];
var regstr = "\\b(?:" + commonWords.join("|") + ")\\b";
var regex = new RegExp(regstr, "ig");
var str = 'She met him where he liked to eat "the best" cheese pizza.';
var arr = str.split(regex);
console.log(arr);// ["", " met ", " where ", " ", " to eat "the best" cheese pizza."]

for(var i = 0; i < arr.length; i++)
  if(arr[i].match(/^\s*$/)) //remove empty strings and strings with only spaces.
    arr.splice(i--, 1);
  else
    arr[i] = arr[i].replace(/^\s+|\s+$/g, ""); //trim spaces from beginning and end

console.log(arr);// ["met", "where", "to eat "the best" cheese pizza."]
console.log(arr.join(", "));// met, where, to eat "the best" cheese pizza.
1 голос
/ 29 июня 2010

Из ОП:

"В основном я хочу использовать non-alphas и мой массив commonWords в качестве разделителей для извлечения фраз."

Это делает оба (в отличие от некоторых других ответов ;-)). Возвращает либо строку, либо массив.

var commonWords = ["she", "he", "him", "liked", "i", "a", "an", "are"];
var SourceStr   = 'She met him where he liked to eat "the best" cheese pizza, didn\'t she, $%&#! Mr. O\'Leary?';

//--- Kill (most) non-alphas, and the keywords replace with tab.
var zRegEx      = eval ('/([^0-9a-z\' ]+)|\\s*\\b(' + commonWords.join ("|") + ')\\b\\s*/ig');
var sPhraseList = SourceStr.replace (zRegEx, '\t');

//-- Trim empty results and leading and trailing delimiters.
sPhraseList     = sPhraseList.replace (/ *\t+ */g, ', '). replace (/, ?, ?/g, ', ');
sPhraseList     = sPhraseList.replace (/(^[, ]+)|([, ]+$)/g, '');

//-- Make optional array:
aPhraseList     = sPhraseList.split (/, */g);

//-- Replace "console.log" with "alert" if you're not using Firebug.
console.log (SourceStr);
console.log (sPhraseList);
console.log (aPhraseList);

.
Возвращает:

"met, where, to eat, the best, cheese pizza, didn't, Mr, O'Leary"

and

["met", "where", "to eat", "the best", "cheese pizza", "didn't", "Mr", "O'Leary"]
0 голосов
/ 29 июня 2010

Эта версия довольно многословна, но также работает с «ленивыми» одинарными и двойными кавычками:

Если массив содержит объект (например, indexOfObject) с флагом сравнения без учета регистра:

if (!Array.prototype.containsObject) Array.prototype.containsObject = function (object, caseInsensitive) {

    for (var i = 0; i < this.length; i++) {

        if (this[i] == object) return true;

        if (!(caseInsensitive && (typeof this[i] == 'string') && (typeof object == 'string'))) continue;

        return (this[i].match(RegExp(object, "i")) != null);

    }

    return false;

}

Выдвинуть объект в массив, если он не пустой:

if (!Array.prototype.pushIfNotEmpty) Array.prototype.pushIfNotEmpty = function (object) {

    if (typeof object == 'undefined') return;
    if ((object && object.length) <= 0) return;

    this.push(object);

}

Канонизация строк:

function canonicalizeString (inString, whitespaceSpecifier) {

    if (typeof inString != 'string') return '';
    if (typeof whitespaceSpecifier != 'string') return '';

    var whitespaceReplacement = whitespaceSpecifier + whitespaceSpecifier;
    var canonicalString = inString.replace(whitespaceSpecifier, whitespaceReplacement);

    var singleQuotedTokens = canonicalString.match(/'([^'s][^']*)'/ig);
    for (tokenIndex in singleQuotedTokens) canonicalString = canonicalString.replace(singleQuotedTokens[tokenIndex], String(singleQuotedTokens[tokenIndex]).replace(" ", whitespaceReplacement));

    var doubleQuotedTokens = canonicalString.match(/"([^"]*)"/ig);
    for (tokenIndex in doubleQuotedTokens) canonicalString = canonicalString.replace(doubleQuotedTokens[tokenIndex], String(doubleQuotedTokens[tokenIndex]).replace(" ", whitespaceReplacement));

    return canonicalString;

}

Веселитесь:

function getSignificantTokensFromStringWithCommonWords (inString, inCommonWordsArray) {

    if (typeof inString != 'string') return [];
    if (typeof (inCommonWordsArray && inCommonWordsArray.length) != 'number') return [];

    var canonicalString = canonicalizeString(inString, "_");

    var commonWords = [];
    for (indexOfCommonWord in inCommonWordsArray) commonWords.pushIfNotEmpty(canonicalizeString(inCommonWordsArray[indexOfCommonWord], "_"));

    var tokenizedStrings = canonicalString.split(" ");

    for (indexOfToken in tokenizedStrings)
    if (commonWords.containsObject(tokenizedStrings[indexOfToken], true))
    tokenizedStrings[indexOfToken] = undefined;





    var responseObject = [];
    for (indexOfToken in tokenizedStrings)
    if (typeof tokenizedStrings[indexOfToken] == 'string')
    responseObject.push(tokenizedStrings[indexOfToken]);

    for (indexOfTokenInResponse in responseObject)
    if (typeof responseObject[indexOfTokenInResponse] == 'string')
    responseObject[indexOfTokenInResponse] = String(responseObject[indexOfTokenInResponse]).replace("__", " ");

    return responseObject;

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...