简体   繁体   中英

How to replace the last string of a matched word in regex?

I want to use regex to replace the letter a with EI from all words that has e at the end of the word and then need to remove the last e from the word. For example:

  • date will become deit

  • cat will remain cat

  • jane will become jein

I have written a regex which replaces a with EI from words that has e at the end but I am not able to remove the last e

My regex : s/a(?=.*e\\b)/EI/g .

The problem with your current regex:

s/a(?=.*e\b)/EI/g.

Is that the .* is greedy , and will match across words. For example, your pattern would target a in banana edible , because .* would detect an e in some other word. Instead, try this find and replace:

Find:

a(?=[A-Za-z]*e\b)

Replace:

ei

Here is a demo showing that the pattern correctly identifies a letters for replacement in words ending in e :

Demo

Find and replace the following

Find: ([a-zA-Z]*)(a)([a-zA-Z]*)(e\\b)

([a-zA-Z]*) ensures zero or more alphabet before first occurrence of a

(a) ensures a is present

([a-zA-Z]*) ensures zero or more alphabet before first occurrence of a

(e\\b) ensures word ends with e

Replace: $1ei$3

$1 - first capture group

instead of second capture group (a) replace with ei

$3 - third capture group

fourth capture group is left out so it removes e at the end

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM