Existe-t-il un moyen de récupérer les positions de caractères (de départ) dans une chaîne de résultats d'une regex match() en Javascript?Retourne les positions d'une regex match() en Javascript?
Répondre
Voici ce que je suis venu avec:
// Finds starting and ending positions of quoted text
// in double or single quotes with escape char support like \" \'
var str = "this is a \"quoted\" string as you can 'read'";
var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;
while (match = patt.exec(str)) {
console.log(match.index + ' ' + patt.lastIndex);
}
exec
retourne un objet avec une propriété index
:
var match = /bar/.exec("foobar");
if (match) {
alert("match found at " + match.index);
}
Et pour plusieurs matches:
var re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
alert("match found at " + match.index);
}
Vous pouvez utiliser la méthode search
de l'objet String
. Cela ne fonctionnera que pour le premier match, mais fera autrement ce que vous décrivez. Par exemple:
"How are you?".search(/are/);
// 4
Cette fn membre retourne un tableau de positions en fonction 0, le cas échéant, du mot d'entrée à l'intérieur l'objet String
String.prototype.matching_positions = function(_word, _case_sensitive, _whole_words, _multiline)
{
/*besides '_word' param, others are flags (0|1)*/
var _match_pattern = "g"+(_case_sensitive?"i":"")+(_multiline?"m":"") ;
var _bound = _whole_words ? "\\b" : "" ;
var _re = new RegExp(_bound+_word+_bound, _match_pattern);
var _pos = [], _chunk, _index = 0 ;
while(true)
{
_chunk = _re.exec(this) ;
if (_chunk == null) break ;
_pos.push(_chunk['index']) ;
_re.lastIndex = _chunk['index']+1 ;
}
return _pos ;
}
Maintenant, essayez
var _sentence = "What do doers want ? What do doers need ?" ;
var _word = "do" ;
console.log(_sentence.matching_positions(_word, 1, 0, 0));
console.log(_sentence.matching_positions(_word, 1, 1, 0));
Vous pouvez aussi saisir des expressions régulières:
var _second = "z^2+2z-1" ;
console.log(_second.matching_positions("[0-9]\z+", 0, 0, 0));
Ici, on obtient l'indice de position de terme linéaire.
De developer.mozilla.org docs sur la méthode String .match()
:
Le tableau retourné a une propriété d'entrée supplémentaire, qui contient la chaîne d'origine qui a été analysé. En outre, il a une propriété indice , qui représente l'indice zéro de la correspondance dans la chaîne .
Lorsque vous traitez avec une expression rationnelle non globale (à savoir, pas de drapeau g
sur votre regex), la valeur retournée par .match()
a une propriété index
... tout ce que vous avez à faire est d'y accéder.
var index = str.match(/regex/).index;
Voici un exemple montrant qu'il travaille ainsi:
var str = 'my string here';
var index = str.match(/here/).index;
alert(index); // <- 10
Je l'ai testé avec succès ce tout le chemin du retour à IE5.
var str = "The rain in SPAIN stays mainly in the plain";
function searchIndex(str, searchValue, isCaseSensitive) {
var modifiers = isCaseSensitive ? 'gi' : 'g';
var regExpValue = new RegExp(searchValue, modifiers);
var matches = [];
var startIndex = 0;
var arr = str.match(regExpValue);
[].forEach.call(arr, function(element) {
startIndex = str.indexOf(element, startIndex);
matches.push(startIndex++);
});
return matches;
}
console.log(searchIndex(str, 'ain', true));
Voici une fonctionnalité intéressante que j'ai découvert récemment, j'ai essayé cela sur la console et il semble fonctionner:
var text = "border-bottom-left-radius";
var newText = text.replace(/-/g,function(match, index){
return " " + index + " ";
});
qui est revenu: "border 6 bas 13 gauche 18 rayon"
Donc, cela semble être ce que vous cherchez.
les fonctions de remplacement ajoutent également des groupes de capture, donc notez que c'est toujours l'entrée * second-to-last * dans la fonction de remplacement 'arguments' qui est la position. Pas "le deuxième argument". Les arguments de la fonction sont "full match, group1, group2, ...., index de correspondance, chaîne complète comparée" –
- 1. javascript regex supprimer guillemet simple en match
- 2. match Regex avec JavaScript
- 3. JavaScript RegEx Elements Match
- 4. problème match Javascript RegEx
- 5. fin de match en ligne javascript regex
- 6. Set Positions retourne E_NOTIMPL
- 7. RegEx a RegEx match
- 8. match regex non gourmand, JavaScript et ASP
- 9. Regex match de question
- 10. Regex match élégant modèle
- 11. match pattern en javascript
- 12. Regex Match PHP Commentaire
- 13. simple regex match
- 14. Regex négative requête match
- 15. Regex question match
- 16. PHP Regex Match parenthèses
- 17. match C# Identifier Unicode en utilisant Regex
- 18. Regex numéro match
- 19. question simple match regex
- 20. Regex match, assez simple:
- 21. Regex Enforcing match de
- 22. match regex inattendu
- 23. Regex en PHP entre/* & */pour preg-match
- 24. Javascript Match et RegExp problème - Comportement étrange
- 25. valeurs Passing en fonction match regex
- 26. regex match différent avec jQuery
- 27. Regex match dans un personnage
- 28. Aide avec multiligne regex match
- 29. match python regex et remplacez
- 30. Luttant avec nombre regex match
Merci @Gumbo pour votre aide – stagas
'match.index + match [0] .length' fonctionne également pour la position finale. –
vraiment agréable - [comparaison gisted ici] (https://gist.github.com/lmmx/eddf11da4236057c89e5) –