Using regular expressions
f[text_, string_, before_, after_] :=
StringCases[text, RegularExpression[".{" <> ToString@before <> "}" <>
string <> ".{" <> ToString@after <> "}"]]
f[text, "entitle", 4, 5]
(*{"God entitle them"}*)
(added by J. M.)
A more compact implementation of the function f[]
is as follows:
f[text_String, string_String, before_Integer, after_Integer] :=
StringCases[text, RegularExpression[ToString[StringForm[
".{`1`}" <> string <> ".{`2`}", before, after]]]]
The ToString[]
is needed here since StringForm[]
, contrary to how it is named, does not return a String[]
object, and thus a conversion has to be done.