2010-06-29 6 views
2

J'ai regardé plusieurs exemples sur la façon d'utiliser regex dans JS mais je n'arrive pas à trouver la bonne syntaxe pour ce dont j'ai besoin. Fondamentalement, j'ai un tableau de mots:Comment extraire des mots et des phrases d'une chaîne en utilisant un tableau en Javascript (JS)?

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

et une chaîne:

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

Fondamentalement, je veux utiliser les non-alphas et mon tableau de commonWords comme délimiteurs pour extraire des phrases. Ce qui précède donne somthing comme ceci:

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

La réponse devrait être: ' 'a rencontré, où manger, le meilleur, le fromage pizza''. "aimé" est dans la liste des mots communs. –

+0

merci! tellement vrai. –

Répondre

1

De l'OP:

"Fondamentalement, je veux utiliser non-alphas et mon tableau de commonWords comme délimiteurs pour extraire des phrases."

Cela fait les deux (contrairement à d'autres réponses ;-)). Il retourne une chaîne ou un tableau.

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); 

.
Ce retour:

"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"] 
2

Vous cherchez quelque chose comme ceci:

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, "")); 

sortie

met where to eat "the best" cheese pizza. 

Version 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

Nice one. L'OP veut 'split 'au lieu de' replace', mais c'est assez similaire. (c'est-à-dire, supprimer le groupe de capture, et peut-être les jetons vides) – Kobi

0

Cette version est assez bavard, mais travaille avec « paresseux » guillemets simples et doubles ainsi:

Si tableau contient l'objet (comme indexOfObject) avec une comparaison insensible à la casse drapeau:

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; 

} 

push objet dans le tableau sinon vide:

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

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

    this.push(object); 

} 

chaînes de canonisant:

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; 

} 

Amusez-vous:

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; 

} 
+0

Vous utiliserez 'getSignificantTokensFromStringWithCommonWords (inString, inCommonWordsArray)' pour utiliser cet extrait. –

Questions connexes