https://theosophy.wiki/w-en/index.php?title=M%C3%B3dulo:String&feed=atom&action=historyMódulo:String - Revision history2024-03-28T20:35:14ZRevision history for this page on the wikiMediaWiki 1.39.4https://theosophy.wiki/w-en/index.php?title=M%C3%B3dulo:String&diff=32578&oldid=prevSysopP: 1 revision2017-06-14T21:17:37Z<p>1 revision</p>
<p><b>New page</b></p><div>--[[ <br />
Este módulo está destinado a proporcionar acceso a las funciones de cadena (string) básicas.<br />
]]<br />
<br />
local str = {}<br />
<br />
--[[<br />
len<br />
<br />
Parametros<br />
s: La cadena a encontrar su longitud <br />
<br />
]]<br />
function str.len( frame )<br />
local new_args = str._getParameters( frame.args, {'s'} );<br />
local s = new_args['s'] or '';<br />
return mw.ustring.len( s )<br />
end<br />
<br />
--[[<br />
sub<br />
<br />
Parametros<br />
s: La cadena donde extraer la subcadena <br />
i: La cadena donde extraer la subcadena.<br />
j: Índice final de la subcadena, por defecto la longitud total, hasta el último carácter.<br />
<br />
]]<br />
function str.sub( frame )<br />
local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } );<br />
local s = new_args['s'] or '';<br />
local i = tonumber( new_args['i'] ) or 1;<br />
local j = tonumber( new_args['j'] ) or -1;<br />
<br />
local len = mw.ustring.len( s );<br />
<br />
-- Convertir negativos para la comprobación de rango<br />
if i < 0 then<br />
i = len + i + 1;<br />
end<br />
if j < 0 then<br />
j = len + j + 1;<br />
end<br />
<br />
if i > len or j > len or i < 1 or j < 1 then<br />
return str._error( 'Índice fuera del rango de la cadena' );<br />
end<br />
if j < i then<br />
return str._error( 'Índices de la cadena no ordenados' );<br />
end<br />
<br />
return mw.ustring.sub( s, i, j )<br />
end<br />
<br />
--[[<br />
match<br />
<br />
Parametros<br />
s: cadena donde se hace la búsqueda <br />
pattern: patrón o cadena a buscar. <br />
start: índice de la cadena dónde empezar a buscar, por defecto 1, el primer carácter. <br />
match: si se encuentran múltiples coincidencias, especifica cuál de ellas devolver. Por defecto es 1, l<br />
la primera coincidencia encontrada. Un número negativo cuenta desde el final, por lo tanto <br />
match = -1 es la última coincidencia. <br />
plain: indica si el patrón debe interpretarse como texto limpio, por defecto 'false'. nomatch: en caso de <br />
no encontrar ninguna coincidencia, devuelve el valor de "nomatch" en lugar de un error. <br />
Si el número match o el índice start están fuera del rango de la cadena, entonces la función genera un error. <br />
También genera un error si no encuentra ninguna coincidencia. <br />
Con el parámetro global ignore_errors = true se suprime el <br />
error y devuelve una cadena vacía.<br />
]]<br />
function str.match( frame )<br />
local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} );<br />
local s = new_args['s'] or '';<br />
local start = tonumber( new_args['start'] ) or 1;<br />
local plain_flag = str._getBoolean( new_args['plain'] or false );<br />
local pattern = new_args['pattern'] or '';<br />
local match_index = math.floor( tonumber(new_args['match']) or 1 );<br />
local nomatch = new_args['nomatch'];<br />
<br />
if s == '' then<br />
return str._error( 'La cadena donde buscar está vacía' );<br />
end<br />
if pattern == '' then<br />
return str._error( 'La cadena de búsqueda está vacía ' );<br />
end<br />
if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then<br />
return str._error( 'Índice d\'inicio fuera del rango de la cadena ' );<br />
end<br />
if match_index == 0 then<br />
return str._error( 'Número de coincidencias fuera de rango' );<br />
end<br />
if plain_flag then<br />
pattern = str._escapePattern( pattern );<br />
end<br />
<br />
local result<br />
if match_index == 1 then<br />
-- Encontrar la primera coincidencia es un caso sencillo.<br />
result = mw.ustring.match( s, pattern, start )<br />
else<br />
if start > 1 then<br />
s = mw.ustring.sub( s, start );<br />
end<br />
<br />
local iterator = mw.ustring.gmatch(s, pattern);<br />
if match_index > 0 then<br />
-- Búsqueda hacia adelante<br />
for w in iterator do<br />
match_index = match_index - 1;<br />
if match_index == 0 then<br />
result = w;<br />
break;<br />
end<br />
end <br />
else<br />
-- Invierte búsqueda<br />
local result_table = {};<br />
local count = 1;<br />
for w in iterator do<br />
result_table[count] = w;<br />
count = count + 1;<br />
end<br />
<br />
result = result_table[ count + match_index ]; <br />
end<br />
end <br />
<br />
if result == nil then<br />
if nomatch == nil then<br />
return str._error( 'Ninguna coincidencia encontrada' );<br />
else<br />
return nomatch;<br />
end<br />
else<br />
return result;<br />
end<br />
end<br />
<br />
--[[<br />
pos<br />
<br />
Parámetros<br />
target: Cadena donde buscar. <br />
pos: Índice del carácter a devolver. <br />
]]<br />
function str.pos( frame )<br />
local new_args = str._getParameters( frame.args, {'target', 'pos'} );<br />
local target_str = new_args['target'] or '';<br />
local pos = tonumber( new_args['pos'] ) or 0;<br />
<br />
if pos == 0 or math.abs(pos) > mw.ustring.len( target_str ) then<br />
return str._error( 'Índice fuera del rango de la cadena' );<br />
end <br />
<br />
return mw.ustring.sub( target_str, pos, pos );<br />
end<br />
<br />
--[[<br />
find<br />
<br />
Parametros<br />
source: Cadena donde buscar. <br />
target: Cadena a buscar o patrón de búsqueda. <br />
start: Índice de la cadena fuente donde empezar a buscar, por defecto 1, el primer carácter. <br />
plain: Indica si la búsqueda debe interpretarse como texto limpio, de lo contrario como patrón Lua. <br />
Por defecto es 'true'.<br />
]]<br />
function str.find( frame )<br />
local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } ); <br />
local source_str = new_args['source'] or '';<br />
local pattern = new_args['target'] or '';<br />
local start_pos = tonumber(new_args['start']) or 1;<br />
local plain = new_args['plain'] or true;<br />
<br />
if source_str == '' or pattern == '' then<br />
return 0;<br />
end <br />
<br />
plain = str._getBoolean( plain );<br />
<br />
local start = mw.ustring.find( source_str, pattern, start_pos, plain )<br />
if start == nil then<br />
start = 0<br />
end<br />
<br />
return start<br />
end<br />
<br />
--[[<br />
replace<br />
<br />
Parámetros<br />
source: Cadena donde buscar <br />
pattern: Cadena de búsqueda o patrón a buscar <br />
replace: Texto de reemplazo <br />
count: Número de ocurrencias a reemplazar, por defecto todas. <br />
plain: Indica si la búsqueda debe interpretarse como texto limpio, de lo contrario como patrón Lua. Por <br />
defecto es 'true' <br />
]]<br />
function str.replace( frame )<br />
local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } ); <br />
local source_str = new_args['source'] or '';<br />
local pattern = new_args['pattern'] or '';<br />
local replace = new_args['replace'] or '';<br />
local count = tonumber( new_args['count'] );<br />
local plain = new_args['plain'] or true;<br />
<br />
if source_str == '' or pattern == '' then<br />
return source_str;<br />
end <br />
plain = str._getBoolean( plain );<br />
<br />
if plain then<br />
pattern = str._escapePattern( pattern );<br />
replace = mw.ustring.gsub( replace, "%%", "%%%%" ); --Sólo es necesario secuencias de escape.<br />
end<br />
<br />
local result;<br />
<br />
if count ~= nil then<br />
result = mw.ustring.gsub( source_str, pattern, replace, count );<br />
else<br />
result = mw.ustring.gsub( source_str, pattern, replace );<br />
end <br />
<br />
return result;<br />
end<br />
<br />
function str.mayuscula(frame) -- Convierte en mayúsculas la primera letra que aparece en la edición de una cadena<br />
local s = frame.args[1] or '';<br />
if s ~= '' then <br />
local cambio = {};<br />
local modo = {};<br />
if string.find(s, '|') ~= nil then -- Enlaces con etiqueta<br />
modo = string.upper(string.match(s,'(|%a)'));<br />
cambio = string.gsub(s,'|%a', modo,1);<br />
elseif string.find(s, '[[]') ~= nil then -- Enlaces sin etiqueta<br />
modo = string.upper(string.match(s,'^(..%a)'));<br />
cambio = string.gsub(s,'^..%a', modo,1);<br />
elseif string.match(s,'^%a') ~= nil then -- Sin enlace<br />
modo = string.upper(string.match(s,'^(%a)'));<br />
cambio = string.gsub(s,'^%a', modo, 1);<br />
else<br />
cambio = s;<br />
end<br />
return cambio;<br />
end<br />
end<br />
<br />
--[[<br />
Función de ayuda que rellena la lista de argumentos, para que el usuario pueda utilizar una combinación de<br />
parámetros con nombre y sin nombre. Esto es importante porque los parámetros con nombre no funcionan igual <br />
que los parámetros sin nombre cuando se encadenan recortes, y cuando se trata de cadenas<br />
a veces se debe conservar o quitar espacios en blanco dependiendo de la aplicación. <br />
]]<br />
function str._getParameters( frame_args, arg_list )<br />
local new_args = {};<br />
local index = 1;<br />
local value;<br />
<br />
for i,arg in ipairs( arg_list ) do<br />
value = frame_args[arg]<br />
if value == nil then<br />
value = frame_args[index];<br />
index = index + 1;<br />
end<br />
new_args[arg] = value;<br />
end<br />
<br />
return new_args;<br />
end <br />
<br />
--[[<br />
Función de ayuda para controlar los mensajes de error.<br />
]]<br />
function str._error( error_str )<br />
local frame = mw.getCurrentFrame();<br />
local error_category = frame.args.error_category or 'Errores detectados por el módulo String';<br />
local ignore_errors = frame.args.ignore_errors or false;<br />
local no_category = frame.args.no_category or false;<br />
<br />
if str._getBoolean(ignore_errors) then<br />
return '';<br />
end<br />
<br />
local error_str = '<strong class="error">Error del módulo String: ' .. error_str .. '</strong>';<br />
if error_category ~= '' and not str._getBoolean( no_category ) then<br />
error_str = '[[Categoría:Wikipedia:' .. error_category .. ']]' .. error_str;<br />
end <br />
<br />
return error_str;<br />
end<br />
<br />
--[[<br />
Función de ayuda para interpretar cadenas booleanas.<br />
]]<br />
function str._getBoolean( boolean_str )<br />
local boolean_value;<br />
<br />
if type( boolean_str ) == 'string' then<br />
boolean_str = boolean_str:lower();<br />
if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0' <br />
or boolean_str == '' then<br />
boolean_value = false;<br />
else<br />
boolean_value = true;<br />
end <br />
elseif type( boolean_str ) == 'boolean' then<br />
boolean_value = boolean_str;<br />
else<br />
error( 'Ningún valor booleano encontrado' );<br />
end <br />
return boolean_value<br />
end<br />
<br />
--[[<br />
Función de ayuda que escapa a todos los caracteres de patrón para que puedan ser tratados<br />
como texto sin formato.<br />
]]<br />
function str._escapePattern( pattern_str )<br />
return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );<br />
end<br />
<br />
return str</div>SysopP