J'ai besoin de trouver 2 mots avant et après un keyrowrd comme ci-dessous:
(?:\S+\s)?\S*(?:\S+\s)?\S*text\S*(?:\s\S+)?\S*(?:\s\S+)?
Voici une regex que j'ai préparée mais ne fonctionne pas pour les espaces intermédiaires.
Here is a testing string with some more testing strings. Keyword - with Result - "testing string with some more"
3 Réponses :
Lorsque vous utilisez \ S * , cela signifie des caractères non blancs, donc vos espaces vont vous gêner.
Je suggère l'expression régulière suivante: (\ S +) \ s * (\ S +) \ s * with \ s * (\ S +) \ s * (\ S +) , ce qui signifie:
(\ S +) : texte qui n'inclut pas de caractères d'espacement (un mot). / s * : zéro ou plusieurs espaces (entre les mots) Après l'avoir utilisé, vous obtiendrez 4 groupes correspondant aux 2 mots avant le avec et 2 mots après.
Essayez le regex ici: https://regex101.com/r/Mk67s2/1
Essayez ci-dessous:
string testString = "Here is a testing string with some more testing strings.";
string keyword = "with";
string pattern = $@"\w+\s+\w+\s+{keyword}\s+\w+\s+\w+";
string match = Regex.Match(testString, pattern).Value;