Plain Text Substitution

  • FH versions: V5 and V6
  • Category: Strings 

It is often desirable to be able to find one sub-string within a longer string, or replace one sub-string with another sub-string within a longer string.

The library functions string.match() and string.gsub() support such operations, but some parameters are Lua Patterns (which are similar to Regular Expressions).

To perform plain text matches or replacements it is necessary to inhibit the magic symbols ^ $ ( ) % . [ ] * + - ? used in Lua Patterns.

The following functions perform the necessary hiding of these magic symbols and are added to the Lua string library. They may be called using either the string.plain(strText) or the strText:plain() format as shown in the Usage block below. The three functions based on existing Lua string library functions accept similar parameters and return similar values.

The code was updated in Dec 2014 to cope with Unicode UTF-8 encoding.

Requires: None

Code

local strMagic = "([%^%$%(%)%%%.%[%]%*%+%-%?])"		-- UTF-8 replacement for "(%W)"

-- Hide magic pattern symbols	^ $ ( ) % . [ ] * + - ?
function plain(strTxt)
	-- Prefix every magic pattern character with a % escape character,
	-- where %% is the % escape, and %1 is the original character capture.
	strTxt = tostring(strTxt or ""):gsub(strMagic,"%%%1")
	return strTxt
end -- function plain

-- matches is plain text version of string.match()
function matches(strTxt,strFind,intInit)
	strFind = tostring(strFind or ""):gsub(strMagic,"%%%1")	-- Hide magic pattern symbols
	return tostring(strTxt or ""):match(strFind,tonumber(intInit))
end -- function matches

-- replace is plain text version of string.gsub()
function replace(strTxt,strOld,strNew,intNum)
	strOld = tostring(strOld or ""):gsub(strMagic,"%%%1")	-- Hide magic pattern symbols
	return tostring(strTxt or ""):gsub(strOld,function() return strNew end,tonumber(intNum))	-- Hide % capture symbols
end -- function replace

-- convert is pattern without captures version of string.gsub()
function convert(strTxt,strOld,strNew,intNum)
	return tostring(strTxt or ""):gsub(tostring(strOld or ""),function() return strNew end,tonumber(intNum))	-- Hide % capture symbols
end -- function convert

Usage

local strInput = "abc 90% xyz"
local strMatch = "90%"
local strPlain = "75%"
print( strInput:plain() )						-->>	abc% 90%%% xyz
print( strInput:gsub( string.plain(strMatch), strPlain:plain() ) )	-->>	abc 75% xyz	1
print( strInput:matches(strMatch, 3) )					-->>	90%
print( strInput:replace(strMatch,strPlain) )				-->>	abc 75% xyz	1
print( strInput:convert( "%d+.", strPlain) )				-->> 	abc 75% xyz	1
Last update: 16 Dec 2020