Module:String2b

Long Wikipedia

This template uses Lua Module:GetParameters {{Lmd|String2}}

The findpagetext function returns the position of a piece of text in the wikitext source of a page. It takes up to four parameters:

  • First positional parameter or |text is the text to be searched for.
  • Optional parameter |title is the page title, defaults to the current page.
  • Optional parameter |plain is either true for a plain search (default), or false for a Lua pattern search.
  • Optional parameter |nomatch is the value returned when no match is found; default is nothing.
Examples
{{#invoke:String2b |findpagetext |text=Youghiogheny}}
{{#invoke:String2b |findpagetext |text=Youghiogheny |nomatch=not found}} → not found
{{#invoke:String2b |findpagetext |text=Youghiogheny |title=Boston Bridge |nomatch=not found}} → not found
{{#invoke:String2b |findpagetext |text=river |title=Boston Bridge |nomatch=not found}} → not found
{{#invoke:String2b |findpagetext |text=[Rr]iver |title=Boston Bridge |plain=false |nomatch=not found}} → not found
{{#invoke:String2b |findpagetext |text=%[%[ |title=Boston Bridge |plain=f |nomatch=not found}} → not found
{{#invoke:String2b |findpagetext |text=%{%{[Cc]oord |title=Boston Bridge |plain=f |nomatch=not found}} → not found

The search is case-sensitive, so Lua pattern matching is needed to find river or River. The last example finds {{coord and {{Coord. The penultimate example finds a wiki-link.

The Template:Findpagetext is a convenience wrapper for this function.


-- Extracted routine from en:Module:String2 rev. 1064289647‎ 
-- requires Lua en:Module:GetParameters

local p = {}

-- findpagetext returns the position of a piece of text in a page
-- First positional parameter or |text is the search text
-- Optional parameter |title is the page title, defaults to current page
-- Optional parameter |plain is either true for plain search (default) or false for Lua pattern search
-- Optional parameter |nomatch is the return value when no match is found; default is nil
p._findpagetext = function(args)
	-- process parameters
	local nomatch = args.nomatch or ""
	if nomatch == "" then nomatch = nil end
	--
	local text = mw.text.trim(args[1] or args.text or "")
	if text == "" then return nil end
	--
	local title = args.title or ""
	local titleobj
	if title == "" then
		titleobj = mw.title.getCurrentTitle()
	else
		titleobj = mw.title.new(title)
	end
	--
	local plain = args.plain or ""
	if plain:sub(1, 1) == "f" then plain = false else plain = true end
	-- get the page content and look for 'text' - return position or nomatch
	local content = titleobj and titleobj:getContent()
	return content and mw.ustring.find(content, text, 1, plain) or nomatch
end
p.findpagetext = function(frame)
	local args = frame.args
	local pargs = frame:getParent().args
	for k, v in pairs(pargs) do
		args[k] = v
	end
	if not (args[1] or args.text) then return nil end
	-- just the first value
	return (p._findpagetext(args))
end

return p