Based on
T-SQL String Manipulation Tips and Techniques, Part 1 especially part Replacing Multiple Contiguous Spaces With a Single Space and idea of Peter Larsson, a SQL Server MVP:
Then, the solution involves three steps (assuming the token is ~):
- Replace in @str each occurrence of ' ' (space) with '~ ' (token plus space).
- Replace in the result of the previous step each occurrence of ' ~' (space plus token) with '' (an empty string).
- Replace in the result of the previous step each occurrence of '~ ' (token plus space) with ' ' (space).
CREATE TABLE #tab(val NVARCHAR(100));
INSERT INTO #tab
SELECT 'Hello'
UNION ALL SELECT 'Heello'
UNION ALL SELECT 'Heeello'
UNION ALL SELECT 'Heeeello'
UNION ALL SELECT 'Heeeeeello'
UNION ALL SELECT 'Heeeeeeeello'
UNION ALL SELECT 'Heeeeeeeeeello';
-- version for one vowel(it can be enhanced to handle other if needed)
SELECT val,
cleaned = REPLACE(
REPLACE(
REPLACE(
REPLACE(REPLACE(val, REPLICATE('e', 8), '^^')
, 'e', '~ ')
, ' ~', '')
, '~ ', 'e')
,'^^','ee')
FROM #tab;
LiveDemo
Output:
╔════════════════╦═════════╗
║ val ║ cleaned ║
╠════════════════╬═════════╣
║ Hello ║ Hello ║
║ Heello ║ Hello ║
║ Heeello ║ Hello ║
║ Heeeello ║ Hello ║
║ Heeeeeello ║ Hello ║
║ Heeeeeeeello ║ Heello ║
║ Heeeeeeeeeello ║ Heeello ║
╚════════════════╩═════════╝