Txt-Substitute not in pair

From Vectorlab
Jump to: navigation, search


Function to substitute characters which are not in a given sequence. For example: ")(" is kept, while ")=" will be replaced with ")(", being here "(" the char given. Load the routine T_SearchReplace before using this. By Orso B. Schmid


{ Orso *********************************************** }
{ search as string for a char not followed by another, substitute it with a replacement char }
{ for example: these chars must always be together ')('}
FUNCTION T_SubstituteNotInPair(str: STRING; char1, char2, replacementChar: CHAR): STRING;
	VAR
		i, posInStr : INTEGER;
		temp_s : STRING;
		boo : BOOLEAN;
		
	BEGIN
		{ search for ')' not followed by '(' }
		temp_s := str;
		WHILE Pos(char1, temp_s) > 0 DO BEGIN
			posInStr := Pos(char1, temp_s);
			
			Insert('@', temp_s, posInStr); { just a temp char whatever }
			Delete(temp_s, posInStr+1, 1); { Delete char1 }
			
			{ if char2 is not after char1 }
			IF (Copy(temp_s, posInStr + 1, 1) <> char2) THEN BEGIN
				Insert(replacementChar, temp_s, posInStr); { substitute char1 forever }
				Delete(temp_s, posInStr+1, 1); { Delete char2 }
			END;
		END;
		
		{ what remains is valid pairs }
		str := T_SearchReplace(temp_s, '@', char1);
		
		{ search for '(' not preceded by ')' }
		temp_s := str;
		WHILE Pos(char2, temp_s) > 0 DO BEGIN
			posInStr := Pos(char2, temp_s);
			
			Insert('@', temp_s, posInStr); { just a temp char whatever }
			Delete(temp_s, posInStr+1, 1); { Delete char2 }
			
			{ if char2 is not after char1 }
			IF (Copy(temp_s, posInStr - 1, 1) <> char1) THEN BEGIN
				Insert(replacementChar, temp_s, posInStr); { substitute char2 forever }
				Delete(temp_s, posInStr+1, 1); { Delete char1 }
			END;
		END;
		
		{ what remains is valid pairs }
		str := T_SearchReplace(temp_s, '@', char2);
		
		T_SubstituteNotInPair := str;
	END;