Shubhang
Shubhang

Reputation: 297

Regex to find the word immediately after a particular word

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

Answers (6)

Frank59
Frank59

Reputation: 3261

"this is my prayer"

.* (my )(\D*)( ).*

group2 in result will your word "prayer"

Upvotes: 0

Dave Sexton
Dave Sexton

Reputation: 11188

Use a look ahead REGEX:

(?<=my )\b\w+\b

Upvotes: 3

stema
stema

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

Rawling
Rawling

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

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

You can use

my\s+\b(\w+)\b

This captures the word after my in the first subgroup.

Upvotes: 2

rmobis
rmobis

Reputation: 27002

For my, use the following regex:

my (\w+)

Upvotes: 0

Related Questions