Ian Vink
Ian Vink

Reputation: 68750

Replacing the end of a word with regex

I have a list of words that I need to replace the endings.

Regex reg = new Regex("(.+)ings");
word = reg.Replace(word,"thly");

I want then abcdeings => abcdethly

but I only get thly

Upvotes: 0

Views: 390

Answers (3)

Cyral
Cyral

Reputation: 14153

Use the $ option at the end of the string, this signifies the end of a string, or alternatively, the \b option which signifies a word boundary

word = Regex.Replace(word, "ings$", "thly");

Upvotes: 3

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

The following regex pattern maches a position following a prefix

(?<=prefix)find\b

In our case we use \w+ as prefix, which denotes one or more word characters

(?<=\w+)ings\b

This works because the prefix is not part of the selected text.

Upvotes: 0

Amir Popovich
Amir Popovich

Reputation: 29836

You can use the \b delimiter:

string word = Regex.Replace("abcdeings",@"ings\b","thly");

Read here.

Upvotes: 2

Related Questions