Append replacement

From Kolmafia
Jump to navigation Jump to search

Function Syntax

buffer append_replacement(matcher match ,buffer buff ,string replace )

buffer append_tail(matcher match ,buffer buff )

  • match is a matcher created with the original string and search pattern
  • buff is the buffer in which the modified string is being accumulated
  • replace is the replacement text for the current match of the search pattern, with the same meanings for special characters as in replace_all()

These two functions are the building blocks for a regular expression-based search and replace operation. Most of the time, you can use the more straightforward replace_string() or replace_all() functions instead; the only time you actually need to use these functions is when the replacement text has to be generated in some special way, rather than being a constant. Both functions return buff, for convenience. To use these functions, you must have a matcher variable which has been created with the desired search pattern and original text, and a buffer variable in which the modified string will be built.

append_replacement() is only valid immediately after find() has returned true for match. It will copy text into the buffer starting after the previous match (or the start of the original string) through the start of the current match, and will then append the replace string.

append_tail() is normally called only once, after find() returns false. It will copy any remaining text into the buffer, after the final match.

Code Samples

This sample will replace every 4-letter word in the input string with its uppercase version.

string cap4(string input)
{
	buffer b;
	matcher m = create_matcher("\\b\\w{4}\\b", input);
	while (m.find()) {
		m.append_replacement(b, m.group().to_upper_case());
	}
	m.append_tail(b);
	return b.to_string();
}

print(cap4("did this script work right?"));
// Output will be: did THIS script WORK right?

See Also

create_matcher()