J'ai une chaîne dans laquelle j'essaie de rechercher toutes les chaînes commençant par mystring/ et se mystring/ par un numéro d'identification à 10 chiffres. Je voudrais sortir une liste de tous ces identifiants avec la chaîne attachée.
Je ne connais pas vraiment regex, mais je suppose que c'est la bibliothèque à utiliser ici. J'ai commencé ci-dessous:
import re
source = 'mystring/1234567890 hello world mystring/2345678901 hello'
re.findall("mystring/",source)
3 Réponses :
Vous pouvez utiliser
print(re.findall(r"\bmystring/(\d{10})(?!\d)", source))
Voir la démo regex .
Détails
\bmystring/ - une limite de mot qui correspond uniquement à mystring comme un mot entier avec / à la fin(\d{10}) - groupe de capture n ° 1: 10 chiffres(?!\d) - non suivi d'un autre chiffre.Whole match: mystring/1234567890 Group 1: 1234567890 Whole match: mystring/2345678901 Group 1: 2345678901
Production:
import re
source = 'mystring/1234567890 hello world mystring/2345678901 hello'
matches = re.finditer(r"\bmystring/(\d{10})(?!\d)", source)
for match in matches:
print("Whole match: {}".format(match.group(0)))
print("Group 1: {}".format(match.group(1)))
Ou utilisez simplement
r"\bmystring/(\d{10})(?!\d)"
qui affichera une liste des ID: ['1234567890', '2345678901'] .
Ici, nous utiliserions deux groupes de capture et mystring deux mystring s, avec et sans ID:
const regex = /(mystring\/([0-9]{10}))/gm;
const str = `hello mystring/1234567890 hello world mystring/2345678901 hellomystring/1234567890 hello world mystring/2345678901 hello`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(mystring\/([0-9]{10}))"
test_str = "hello mystring/1234567890 hello world mystring/2345678901 hellomystring/1234567890 hello world mystring/2345678901 hello"
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Si cette expression n'était pas souhaitée, elle peut être modifiée / changée dans regex101.com .
jex.im visualise les expressions régulières:
(mystring\/([0-9]{10}))
Vous pouvez utiliser une limite de mot \b pour empêcher mystring de faire partie d'un mot plus grand, puis faire correspondre une barre oblique suivie de 10 chiffres \d{10} utilisant un quantificateur :
(?<=\bmystring/)\d{10}(?!\S)
Par exemple:
['mystring/1234567890', 'mystring/2345678901']
Résultat:
import re
source = 'mystring/1234567890 hello world mystring/2345678901 hello'
print(re.findall(r"\bmystring/\d{10}",source))
Si vous souhaitez lister uniquement les chiffres, vous pouvez également utiliser un lookbehind positif:
\bmystring/\d{10}
(?<=\bmystring/) positif en arrière, affirmer que ce qui est directement à gauche est mystring\d{10} correspond à 10 chiffres(?!\S) Lookahead négatif, affirmer que ce qui est directement à droite n'est pas un caractère sans espace
Voulez-vous dire comme
\bmystring/\d{10}? regex101.com/r/5GLZEn/1oui, bien que cela ne semble pas fonctionner avec
re.findall("\bmystring/\d{10}",source)pour moi. Comment adopteriez-vous cela pour python?Vous pouvez utiliser
re.findall(r"\bmystring/\d{10}",source)démo@Thefourthbird parfait, merci!
(mystring/.*?)(\d{10})