0
votes

This question has no specific regex engine in mind.

I need to, when the word ends with a specific suffix, replace all occurrences of a specific character in the word and then additionally remove its suffix. For consistency, I will use vim-like regex-replace syntax. Here is what I have so far:

s/a(\w*)s\b/e\1/g

This finds an occurrence of an "a" character in any word ending with an "s" and replaces it with an "e", while additionally removing the "s" but does not overlap in the sense that it cannot match and replace multiple occurrences of a character in the same word.

A solution must match and replace one or more characters while also removing the suffix.

Some example behavior:

cars -> cer
creators -> creetor
bowling -> bowling
bowling balls -> bowling bell
castration -> castration
castrations -> cestretion
1
I'm afraid you can't do that with a single replace.Toto
I had a hunch that that was the case. This was an interview question and I gave the same answer: it's impossible with just a single regex-replacearlyon

1 Answers

1
votes

I'm not sure if you can do all of your requirements with only a regex. But, if you use (?:(\w*?a\w*))*(?=s\b) It will match all words with at least a single a in the word and the suffix. But the replacement could then be done within the programming language. So you could use re.findall(r"\b(\w*?a\w*)(?=s\b)",text) in Python and then: [word.replace("a","e") for word in re.findall(r"\b(\w*?a\w*)(?=s\b)",x)]

Which would give you: ['cer', 'creetor', 'bell', 'cestretion']