Reputation: 297
I want to find the word immediately after a particular word in a string using a regex. For example, if the word is 'my',
"This is my prayer"- prayer
"this is my book()"- book
Is it possible using regex?
Upvotes: 8
Views: 13001
Reputation: 3261
"this is my prayer"
.* (my )(\D*)( ).*
group2 in result will your word "prayer"
Upvotes: 0
Reputation: 92986
The regex would be
(?<=\bmy\s+)\p{L}+
\p{L}+
is a sequence of letters. The \p{L}
is a Unicode code point with the property "Letter", so it matches a letter in any language.
(?<=\bmy\s+)
is a lookbehind assertion, that ensures thet word "my" is before
Upvotes: 9
Reputation: 50114
If my
is taken from user input,
static string GetWordAfter(string word, string phrase)
{
var pattern = @"\b" + Regex.Escape(word) + @"\s+(\w+)";
return Regex.Match(phrase, pattern, RegexOptions.IgnoreCase).Groups[1].Value;
}
...
string wordAfterMy = GetWordAfter("my", "this is my book()"); // gives book
This will return an empty string if there is no match.
Upvotes: 0
Reputation: 74028
You can use
my\s+\b(\w+)\b
This captures the word after my in the first subgroup.
Upvotes: 2