3
votes

Regex pour trouver 2 mots avant et après un mot-clé

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"


0 commentaires

3 Réponses :


4
votes

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


0 commentaires

3
votes

Essayez ceci:

([a-zA-Z]+\s+){2}with(\s+[a-zA-Z]+){2}

Voici la démo


0 commentaires

0
votes

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;


0 commentaires