javascript tome x - RegExp
Transcription
javascript tome x - RegExp
R eg Ex p – Expressions Régulières J AVA S C R I P T (Programmation Internet) V O L . X Pour Débutants J.B. Dadet DIASOLUKA Luyalu Nzoyifuanga +243 - 851278216 - 899508675 - 991239212 - 902263541 - 813572818 CHAPITRE 17 : Les Expressions régulières (RegExp) : L’objet RegExp décrit un modèle de chaîne de caractères à utiliser dans une expression régulière. Les Expressions Régulières servent à une comparaison (pattern-matching) et la recherche & remplacement ("search-and-replace") sur du texte. Syntaxe : /modele/modificateurs; Exemple : var regexp = /model/ig Les Modificateurs : Modifient le mode de l’opération : Modificateur Action i Respect de la case : i = casse insensible, par défaut = casse sensible. g Recherche globale (sur toute la chaîne, pas seulement la première occurrence = global search). m Correspondance (match) multiligne. J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X Parenthèses et Crochets = [square] Brackets dans le modèle : Ils spécifient une étendue (rangée) de caractères : Signification des Expressions dans les Crochets : Expression Signification [abc] Toute lettre d’alphabet contenue entre les crochets. [^abc] Toute lettre d’alphabet autre que celles entre les crochets. [0-9] N’importe quel chiffre (digit) décimal dans l’étendue spécifié dans les crochets, les bornes comprises. [^0-9] Tout chiffre en dehors de la rangée spécifiée les bornes incluses (abc) La chaîne exacte spécifiée. Exemple manipulation de dates : <script type="text/javascript"> "use strict"; let reDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/, match = reDate.exec('2020-12-31'), an = match[1], mois = match[2], jour = match[3], jourx = match[4]; console.log(reDate); console.log(match); console.log(jour); console.log(mois); console.log(an); console.log(jourx); </script> RegExp - 2 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X ou, pour éviter l’indexation, <script type="text/javascript"> "use strict"; const reDate = /(?<an>[0-9]{4})-(?<mois>[0-9]{2})(?<jour>[0-9]{2})/, date = '2018-04-30', match = reDate.exec(date), an = match.groups.an, // 2018 mois = match.groups.mois, // 04 jour = match.groups.jour; // 30 console.log(reDate); console.log(match); console.log(jour); console.log(mois); RegExp - 3 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log(an); console.log( date.replace(reDate, '$<jour>-$<mois>-$<an>') ); // Changement format de date. </script> Avec Yandex (ça ne marche pas avec Firefox Quantum 62.0.2) : Firefox : LookAhead : RegExp - 4 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X Par exemple, comment extraire le sigle monétaire dans un prix : <script type="text/javascript"> "use strict"; const reLookahead = /\D+(?=\d+)/, match = reLookahead.exec('Roubles123.45'); console.log( console.log( console.log( console.log( console.log( console.log( "match =",match ); `match["index"] = ${match["index"]}` ); 'match["length"] =',match["length"] ); "match.length =",match.length ); "match['input'] =",match['input'] ); "match[0] =",match[0] ); console.log( match[1] ); </script> Bien satisfaits ? Voyons les variantes suivantes : Tous les nombres : <script type="text/javascript"> "use strict"; const reLookahead = /\D+(\d+.)+(\d+.)+(\d+.)+(\d+.)+/, RegExp - 5 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log( "match =",match ); // match = Array(5) [ // "Mon IP : 123.45.73.255", "123.", "45.", "73.", "255" // ] console.log( `match["index"] = ${match["index"]}` ); // match["index"] = 0 console.log( 'match["length"] =',match["length"] ); // match["length"] = 5 console.log( "match.length =",match.length ); // match.length = 5 console.log( "match['input'] =",match['input'] ); // match['input'] = Mon IP : 123.45.73.255 console.log( "match[0] =",match[0] ); // match[0] = Mon IP : 123.45.73.255 console.log( console.log( console.log( console.log( "match[1] "match[2] "match[3] "match[4] =",match[1] =",match[2] =",match[3] =",match[4] ); ); ); ); // // // // match[1] match[2] match[3] match[4] = = = = 123. 45. 73. 255 console.log( "match[5] =",match[5] ); // match[5] = undefined </script> Le dernier nombre : <script type="text/javascript"> "use strict"; const reLookahead = /\D+(\d+.)+/, match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log("match =",match); // match = // Array [ "Mon IP : 123.45.73.255", "255" ] RegExp - 6 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log(`match["index"] = ${match["index"]}`); // match["index"] = 0 console.log('match["length"] =',match["length"]); // match["length"] = 2 console.log("match.length =",match.length); // match.length = 2 console.log("match['input'] =",match['input']); // match['input'] = Mon IP : 123.45.73.255 console.log("match[0] =",match[0]); // match[0] = Mon IP : 123.45.73.255 console.log("match[1] =",match[1]); // match[1] = 255 console.log("match[2] =",match[2]); // match[2] = undefined console.log("match[3] =",match[3]); // match[3] = undefined console.log("match[4] =",match[4]); // match[4] = undefined console.log("match[5] =",match[5]); // match[5] = undefined </script> Le premier nombre : <script type="text/javascript"> "use strict"; const reLookahead = /\D+(\d+)/, match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log("match =",match); // match = // Array [ "Mon IP : 123.45.73.255", "255" ] console.log(`match["index"] = ${match["index"]}`); // match["index"] = 0 console.log('match["length"] =',match["length"]); RegExp - 7 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu // JavaScript Tome-X match["length"] = 2 console.log("match.length =",match.length); // match.length = 2 console.log("match['input'] =",match['input']); // match['input'] = Mon IP : 123.45.73.255 console.log("match[0] =",match[0]); // match[0] = Mon IP : 123.45.73.255 console.log("match[1] =",match[1]); // match[1] = 255 console.log("match[2] =",match[2]); // match[2] = undefined console.log("match[3] =",match[3]); // match[3] = undefined console.log("match[4] =",match[4]); // match[4] = undefined console.log("match[5] =",match[5]); // match[5] = undefined </script> <script type="text/javascript"> "use strict"; const reLookahead = /\D+(.\d+)/, match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log("match =",match); // match = // Array [ "Mon IP : 123", "123" ] console.log(`match["index"] = ${match["index"]}`); // match["index"] = 0 console.log('match["length"] =',match["length"]); // match["length"] = 2 console.log("match.length =",match.length); // match.length = 2 RegExp - 8 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log("match['input'] =",match['input']); // match['input'] = Mon IP : 123.45.73.255 console.log("match[0] =",match[0]); // match[0] = Mon IP : 123 console.log("match[1] =",match[1]); // match[1] = 123 console.log("match[2] =",match[2]); // match[2] = undefined console.log("match[3] =",match[3]); // match[3] = undefined console.log("match[4] =",match[4]); // match[4] = undefined console.log("match[5] =",match[5]); // match[5] = undefined </script> <script type="text/javascript"> "use strict"; const reLookahead = /\D+(\d+).+/, match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log("match =",match); // match = // Array [ "Mon IP : 123", "123" ] console.log(`match["index"] = ${match["index"]}`); // match["index"] = 0 console.log('match["length"] =',match["length"]); // match["length"] = 2 console.log("match.length =",match.length); // match.length = 2 console.log("match['input'] =",match['input']); // match['input'] = Mon IP : 123.45.73.255 console.log("match[0] =",match[0]); // match[0] = Mon IP : 123 RegExp - 9 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log("match[1] =",match[1]); // match[1] = 123 console.log("match[2] =",match[2]); // match[2] = undefined console.log("match[3] =",match[3]); // match[3] = undefined console.log("match[4] =",match[4]); // match[4] = undefined console.log("match[5] =",match[5]); // match[5] = undefined </script> Les vicissitudes, trapes, caprices… <script type="text/javascript"> "use strict"; const // reLookahead = /\D+(\.d+)/, // Err // reLookahead = /\D+.(.\d+)/, reLookahead = /\D+.(\d{3})+/, // ou match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log("match =",match); // match = // Array [ "Mon IP : 123", "23" ] console.log(`match["index"] = ${match["index"]}`); // match["index"] = 0 console.log('match["length"] =',match["length"]); // match["length"] = 2 console.log("match.length =",match.length); // match.length = 2 console.log("match['input'] =",match['input']); // match['input'] = Mon IP : 123.45.73.255 console.log("match[0] =",match[0]); // match[0] = Mon IP : 123 RegExp - 10 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log("match[1] =",match[1]); // match[1] = 123 console.log("match[2] =",match[2]); // match[2] = undefined console.log("match[3] =",match[3]); // match[3] = undefined console.log("match[4] =",match[4]); // match[4] = undefined console.log("match[5] =",match[5]); // match[5] = undefined </script> vs <script type="text/javascript"> "use strict"; const // reLookahead = /\D+(\.d+)/, // Err // reLookahead = /\D+.(.\d+)/, reLookahead = /\D+.(\d+)+/, // ou match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log("match =",match); // match = // Array [ "Mon IP : 123", "23" ] console.log(`match["index"] = ${match["index"]}`); // match["index"] = 0 console.log('match["length"] =',match["length"]); // match["length"] = 2 console.log("match.length =",match.length); // match.length = 2 console.log("match['input'] =",match['input']); // match['input'] = Mon IP : 123.45.73.255 console.log("match[0] =",match[0]); // match[0] = Mon IP : 23 RegExp - 11 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log("match[1] =",match[1]); // match[1] = 23 console.log("match[2] =",match[2]); // match[2] = undefined console.log("match[3] =",match[3]); // match[3] = undefined console.log("match[4] =",match[4]); // match[4] = undefined console.log("match[5] =",match[5]); // match[5] = undefined </script> <script type="text/javascript"> "use strict"; const reLookahead = /\D+(\d+)(\d+)(\d+)/, match = reLookahead.exec( 'Mon IP : 123.45.73.255'); console.log( "match =",match ); // match = Array(5) [ // "Mon IP : 123.45.73.255", "123.", "45.", "73.", "255" // ] console.log( `match["index"] = ${match["index"]}` ); // match["index"] = 0 console.log( 'match["length"] =',match["length"] ); // match["length"] = 4 console.log( "match.length =",match.length ); // match.length = 4 console.log( "match['input'] =",match['input'] ); // match['input'] = Mon IP : 123.45.73.255 console.log( "match[0] =",match[0] ); // match[0] = Mon IP : 123 console.log( "match[1] =",match[1] ); // match[1] = 1 console.log( "match[2] =",match[2] ); // match[2] = 2 RegExp - 12 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log( "match[3] =",match[3] ); // match[3] = 3 console.log( "match[4] =",match[4] ); // match[4] = undefined console.log( "match[5] =",match[5] ); // match[5] = undefined </script> LookBehind : Par exemple, extraire le prix sans le sigle monétaire : Sautez les nondigits et prendre les premiers digits avant d’autres non-digits. À ne pas confondre avec un éventuel « LookReverse », ici c’est « sauter » : « regarder après… » ou « lookPast… ». LookBehind positif : Positive lookbehind assertion : Un non-digit DOIT exister : <script type="text/javascript"> "use strict"; const reLookbehind = /(?<=\D)\d+.\d+.\d+.\d+/, match = reLookbehind.exec('Mon IP : 123.45.73.255'); console.log( console.log( console.log( console.log( console.log( console.log( "match =",match ); `match["index"] = ${match["index"]}` ); 'match["length"] =',match["length"] ); "match.length =",match.length ); "match['input'] =",match['input'] ); "match[0] =",match[0] ); console.log( match[1] ); </script> Avec Yandex Version 18.11.1.385 beta : RegExp - 13 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X Firefox Quantum 62.0.2 n’a pas cette fonctionnalité ! LookBehind négatif : Negative lookbehind assertion : Une valeur NE DOIT PAS exister : <script type="text/javascript"> "use strict"; const reLookbehindNeg = /(?<!\Di)\d+.\d+.\d+.\d+/, match = reLookbehindNeg.exec( 'Mon IP : 123.45.73.255'); console.log( console.log( console.log( console.log( console.log( RegExp "match =",match ); // $ `match["index"] = ${match["index"]}` ); // $ 'match["length"] =',match["length"] ); // $ "match.length =",match.length ); // $ "match['input'] =",match['input'] ); // $ - 14 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X console.log( "match[0] =",match[0] ); // $ console.log( match[1] ); // $ </script> « Parser » le IP : <script type="text/javascript"> "use strict"; const reLookaheadNeg = /\D+(\d+).(\d+).(\d+).(\d+)/, match = reLookaheadNeg.exec( 'Mon IP : 123.45.73.255'); console.log( console.log( console.log( console.log( console.log( RegExp "match =",match ); `match["index"] = ${match["index"]}` ); 'match["length"] =',match["length"] ); "match.length =",match.length ); "match['input'] =",match['input'] ); - 15 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu console.log( console.log( console.log( console.log( console.log( console.log( </script> RegExp "match[0] "match[1] "match[2] "match[3] "match[4] "match[5] JavaScript Tome-X =",match[0] =",match[1] =",match[2] =",match[3] =",match[4] =",match[5] - 16 / 23 ); ); ); ); ); ); - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu RegExp - 17 / 23 JavaScript Tome-X - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X Les Métacaractères : Caractères spéciaux (ayant signification spéciale) : Métacaractère Représente (correspond à, recherche) . (point, period) Un seul caractère à part « saut de ligne » (newline) ou « fin dot, de ligne » (line terminator). \0 Caractère NUL \b Correspondance au début/fin d’un Mot \B Correspondance pas au début/fin d’un Mot \d Chiffre (digit) décimal \D Pas un chiffre (non-digit) décimal \f Caractère « form feed » (avancement feuille). \n Caractère « new line » (Avancement ligne) \r Caractère « carriage return » (Retour chariot) \s Caractère « White space » Barre d’espacement \S Tout caractère autre que l’espace (non-whitespace character) \t « tab character » (Caractère de tabulation) \uxxxx Caractère Unicode spécifié, en Hexadécimal xxxx \v « vertical tab character » (tabulation verticale) \w Mot (word character) \W Non-mot (non-word character) RegExp - 18 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X \xxx Caractère spécifié par le nombre octal xxx \xdd Caractère spécifié par le nombre hexadécimal dd Les Quantificateurs (facteurs d’itération) : Itérateur Signification n+ Toute chaîne contenant au moins 1 n n* Toute chaîne contenant zéro ou plusieurs (un nombre quelconque d’) occurrences de n n? Toute chaîne contenant zéro ou UNE (tout au plus UNE) occurrences de n n{X} Toute chaîne contenant une séquence de X n n{X,Y} Chaîne contenant une séquence de X à Y n n{X,} Toute chaîne contenant une séquence d’au moins X n n$ Toute chaîne se terminant par n ^n Toute chaîne commençant par n ?=n Toute chaîne suivie de la chaîne n spécifiée ?!n Toute chaîne non suivie de la chaîne n spécifiée Propriétés de l’Object RegExp : Propriété Description constructor Renvoie la fonction qui a créé le prototype de l’objet RegExp global Vérifie si le modificateur « g » est activé ignoreCase Vérifie si le modificateur « i »" est activé lastIndex Dernier index à partir duquel démarrer la prochaine comparaison RegExp - 19 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X multiline Vérifie si le modificateur « m » est activé source Renvoie le texte (ou chaîne) du modèle (ou pattern) RegExp Méthodes de l’objet RegExp : Méthode Description compile() Compile une expression régulière (Dépréciée dans la version 1.5). exec() Teste un match dans une chaîne. Renvoie le premier match test() Teste un match dans une chaîne. Renvoie true ou false toString() Renvoie la valeur de la chaîne de l’expression régulière Propriétés de RegExp : <script> console.log(RegExp.prototype); </script> Exécution : 1 {constructor: ƒ, exec: ƒ, …} A compile:ƒ compile() B constructor:ƒ RegExp() C dotAll:(...) D exec:ƒ exec() E flags:(...) F global:(...) G ignoreCase:(...) H multiline:(...) I source:(...) J sticky:(...) K test:ƒ test() L toString:ƒ toString() RegExp - 20 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X M unicode:(...) N Symbol(Symbol.match):ƒ [Symbol.match]() O Symbol(Symbol.replace):ƒ [Symbol.replace]() P Symbol(Symbol.search):ƒ [Symbol.search]() Q Symbol(Symbol.split):ƒ [Symbol.split]() R get dotAll:ƒ dotAll() S get flags:ƒ flags() T get global:ƒ global() U get ignoreCase:ƒ ignoreCase() V get multiline:ƒ multiline() W get source:ƒ source() X get sticky:ƒ sticky() Y get unicode:ƒ unicode() Z __proto__:Object Propriétés de RegExp avec Object . getOwnPropertyNames ( RegExp ) : Array [ "input", "lastMatch", "lastParen", "leftContext", "rightContext", "$1", "$2", "$3", "$4", "$5", … ] 0: "input" 1: "lastMatch" 2: "lastParen" 3: "leftContext" 4: "rightContext" 5: "$1" 6: "$2" 7: "$3" 8: "$4" 9: "$5" 10: "$6" 11: "$7" 12: "$8" 13: "$9" 14: "$_" 15: "$&" 16: "$+" 17: "$`" 18: "$'" RegExp - 21 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X 19: "prototype" 20: "length" 21: "name" length: 22 __proto__: Array [] Propriétés de RegExp avec For(i in RegExp) : input. lastMatch. undefined lastParen. leftContext. rightContext. $1. $2. $3. $4. $5. $6. $7. $8. $9. Mots-clés : RegExp, modèle de chaîne, expression régulière, Expressions Régulières, comparaison, pattern-matching, recherche, remplacement, searchand-replace, Métacaractères,Caractères spéciaux Kinshasa, le jeudi, 4. avril 2019 (10:48 ). DIASOLUKA Nz. Luyalu Docteur en Médecine, Chirurgie & Accouchements (1977), CNOM : 0866 - Spécialiste en ophtalmologie (1980) RegExp - 22 / 23 - jeudi, 4. avril 2019 (10:48 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-X Informaticien-amateur, Programmeur et WebMaster. Chercheur indépendant, autonome et autofinancé, bénévole, sans aucun conflit d’intérêt ou liens d'intérêts ou contrainte promotionnelle avec qui qu’il soit ou quelqu’organisme ou institution / organisation que ce soit, étatique, paraétatique ou privé, industriel ou commercial en relation avec le sujet présenté. +243 - 851278216 - 899508675 - 995624714 - 902263541 - 813572818 [email protected] RegExp - 23 / 23 - jeudi, 4. avril 2019 (10:48 )