Penlight 字符串处理高级操作指南
概述
Penlight 是一个强大的 Lua 工具库,提供了许多实用的字符串处理功能。本文将详细介绍 Penlight 中字符串模块的高级特性,包括扩展字符串方法、字符串模板以及字符串 I/O 操作等。
扩展字符串方法
Penlight 从 Python 借鉴了许多实用的字符串方法,这些方法通过 stringx
模块提供:
常用字符串判断方法
isalpha()
: 检查字符串是否只包含字母isdigit()
: 检查字符串是否只包含数字startswith()
: 检查字符串是否以指定前缀开头endswith()
: 检查字符串是否以指定后缀结尾
stringx.import()
print(('bonzo.dog'):endswith {'.dog','.cat'}) -- true
print(('bonzo.txt'):endswith {'.dog','.cat'}) -- false
字符串格式化方法
ljust(width, fillchar)
: 左对齐字符串rjust(width, fillchar)
: 右对齐字符串strip()
: 去除两端空白lstrip()
: 去除左端空白rstrip()
: 去除右端空白
print((' stuff'):ljust(20,'+')) -- '++++++++++++++ stuff'
print((' stuff '):strip()) -- 'stuff'
行迭代器
lines()
方法可以方便地迭代字符串中的每一行:
for s in ('one\ntwo\nthree\n'):lines() do
print(s)
end
-- 输出:
-- one
-- two
-- three
字符串模板
Penlight 提供了强大的字符串模板功能,可以方便地进行变量替换。
基本模板
local Template = require('pl.text').Template
local t = Template('${here} is the $answer')
print(t:substitute {here = 'Lua', answer = 'best'})
-- 输出: Lua is the best
缩进感知模板
indent_substitute
方法特别适合处理代码块,它会自动调整缩进:
local t = Template [[
for i = 1,#$t do
$body
end
]]
local body = Template [[
local row = $t[i]
for j = 1,#row do
fun(row[j])
end
]]
print(t:indent_substitute {body=body, t='tbl'})
格式化操作符
Penlight 还提供了类似 Python 的格式化操作符 %
:
text.format_operator()
print('%s[%d]' % {'dog',1}) -- dog[1]
print('$animal[$num]' % {animal='dog',num=1}) -- dog[1]
另一种模板风格
pl.template
模块提供了更灵活的模板处理方式,允许在模板中直接嵌入 Lua 代码:
模板规则
- 以
#
开头的行是 Lua 代码 $(...)
中的内容是 Lua 表达式
local template = require 'pl.template'
local tmpl = [[
<ul>
# for i,val in ipairs(T) do
<li>$(i) = $(val:upper())</li>
# end
</ul>
]]
local res = template.substitute(tmpl, {
ipairs = ipairs,
T = {'one','two','three'}
})
高级用法
可以自定义分隔符和转义字符,适合生成各种语言的代码:
local templ = [[
#include <lua.h>
> for _,f in ipairs(mod) do
static int l_$(f.name) (lua_State *L) {
}
> end
]]
print(subst(templ,{
_escape = '>',
ipairs = ipairs,
mod = {name = 'baggins'; {name='frodo'}, {name='bilbo'}}
}))
字符串 I/O 操作
pl.stringio
模块提供了类似文件操作的字符串处理功能:
字符串读取
local stringio = require 'pl.stringio'
local f = stringio.open 'first line\n10 20 30\n'
print(f:read()) -- first line
print(f:read('*n','*n','*n')) -- 10 20 30
字符串构建
local f = stringio.create()
f:write('hello')
f:write(' world')
print(f:value()) -- hello world
总结
Penlight 的字符串处理功能极大地扩展了 Lua 原生字符串库的能力,提供了更加方便和强大的字符串操作方法。无论是简单的字符串判断、格式化,还是复杂的模板处理和代码生成,Penlight 都能提供优雅的解决方案。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考