function trim1(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
-- from PiL2 20.4 function trim2(s)
return s:match "^%s*(.-)%s*$"
end
-- variant of trim1 (match) function trim3(s)
return s:gsub("^%s+", ""):gsub("%s+$", "")
end
-- two gsub's function trim4(s)
return s:match"^%s*(.*)":match"(.-)%s*$"
end
-- variant of trim3 (match) function trim5(s)
return s:match'^%s*(.*%S)' or ''
end
-- warning: has bad performance when s:match'^%s*$' and #s is large function trim6(s)
return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end
-- fixes performance problem in trim5.
-- note: the '()' avoids the overhead of default string capture.
-- This overhead is small, ~ % for successful whitespace match call
-- alone, and may not be noticeable in the overall benchmarks here,
-- but there's little harm either. Instead replacing the first `match`
-- with a `find` has a similar effect, but that requires localizing
-- two functions in the trim7 variant below. local match = string.match
function trim7(s)
return match(s,'^()%s*$') and '' or match(s,'^%s*(.*%S)')
end
-- variant of trim6 (localize functions) local find = string.find
local sub = string.sub
function trim8(s)
local i1,i2 = find(s,'^%s*')
if i2 >= i1 then s = sub(s,i2+) end
local i1,i2 = find(s,'%s*$')
if i2 >= i1 then s = sub(s,,i1-) end
return s
end
-- based on penlight 0.7. function trim9(s)
local _,i1 = find(s,'^%s*')
local i2 = find(s,'%s*$')
return sub(s,i1+,i2-)
end
-- simplification of trim8 function trim10(s)
local a = s:match('^%s*()')
local b = s:match('()%s*$', a)
return s:sub(a,b-)
end
-- variant of trim9 (match) function trim11(s)
local n = s:find"%S"
return n and s:match(".*%S", n) or ""
end
-- variant of trim6 (use n position)
-- http://lua-users.org/lists/lua-l/2009-12/msg00904.html function trim12(s)
local from = s:match"^%s*()"
return from > #s and "" or s:match(".*%S", from)
end
-- variant of trim11 (performs better for all
-- whitespace string). See Roberto's comments
-- on ^%s*$" v.s. "%S" performance:
-- http://lua-users.org/lists/lua-l/2009-12/msg00921.html do
require 'lpeg'
local space = lpeg.S' \t\n\v\f\r'
local nospace = - space
local ptrim = space^ * lpeg.C((space^ * nospace^)^)
local match = lpeg.match
function trim13(s)
return match(ptrim, s)
end
end
-- lpeg. based on http://lua-users.org/lists/lua-l/2009-12/msg00921.html do
require 'lpeg'
require 're'
local ptrim = re.compile"%s* {(%s* %S+)*}"
local match = lpeg.match
function trim14(s)
return match(ptrim, s)
end
end
-- variant with re module. require 'trim'
local trim15 = trim
-- C implementation (see separate trim.c file) -- test utilities local function trimtest(trim)
assert(trim'' == '')
assert(trim' ' == '')
assert(trim' ' == '')
assert(trim'a' == 'a')
assert(trim' a' == 'a')
assert(trim'a ' == 'a')
assert(trim' a ' == 'a')
assert(trim' a ' == 'a')
assert(trim' ab cd ' == 'ab cd')
assert(trim' \t\r\n\f\va\000b \r\t\n\f\v' == 'a\000b')
end local function perftest(f, s)
local time = os.clock -- os.time or os.clock
local t1 = time()
for i=, do
f(s)f(s)f(s)f(s)f(s)f(s)f(s)f(s)f(s)f(s)
end
local dt = time() - t1
io.stdout:write(string.format("%4.1f",dt) .. ' ')
end local trims = {trim1, trim2, trim3, trim4, trim5, trim6, trim7,
trim8, trim9, trim10, trim11, trim12, trim13, trim14, trim15} -- correctness tests
for _,trim in ipairs(trims) do
trimtest(trim)
end -- performance tests
for j=, do
for i,trim in ipairs(trims) do
io.stdout:write(string.format("%2d",i) .. ": ")
perftest(trim, "")
perftest(trim, "abcdef")
perftest(trim, " abcdef ")
perftest(trim, "abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef")
perftest(trim, " a b c d e f g h i j k l m n o p q r s t u v w x y z A B C ")
perftest(trim, " a ")
perftest(trim, " ")
print()
end
end

原文地址:http://lua-users.org/wiki/StringTrim

用Lua实现string的trim()方法的更多相关文章

  1. IE8下String的Trim()方法失效的解决方法

    String的Trim()方法失效,在ie8下是有这样的情况的,解决方法也很简单使用$.trim(str)即可,需要的朋友可以了解下 用jquery的trim()方法,$.trim(str)就可以了.

  2. JS中String添加trim()方法

    这么牛的JS竟然还要自己封装trim方法. 下面利用prototype和正则表达式的添加方式添加trim(): <script language="javascript"&g ...

  3. 自己实现String.prototype.trim方法

    今天呢 知乎看到一道题 说是网易面试题,要求自己写一个trim()方法, 实现 var str = "   a   sd  "; 去掉字符串两端的空格. 直接上码 var str ...

  4. js在IE8+兼容String没有trim方法,写一个兼容ie8一下的浏览器的trim()方法

    方法一: String.prototype.trim = function(){ return Trim(this);}; function LTrim(str) {    var i;     fo ...

  5. 字符串String的trim()方法

    用来删除字符串两端的空白字符并返回,trim方法并不影响原来的字符串本身,它返回的是一个新的字符串 String a = "  Hello World  "; String b = ...

  6. IE8下String的Trim()方法失效的解决方案

    简洁方便 用jquery的trim()方法,$.trim(str)就可以了.

  7. spring框架中一个跟String的trim方法一样的方法

    @Test public void testTrimWhitespace() throws Exception { assertEquals(null, StringUtils.trimWhitesp ...

  8. java中String的.trim()方法

    该方法去除两边的空白符 原理: 看看源码实现 public String trim() { int len = value.length; ; char[] val = value; /* avoid ...

  9. java String类 trim() 方法源码分析

    public String trim() {        int arg0 = this.value.length;   //得到此字符串的长度        int arg1 = 0;   //声 ...

随机推荐

  1. C语言 · 求最大公约数

    算法提高 求最大公约数   时间限制:1.0s   内存限制:512.0MB      编写一函数gcd,求两个正整数的最大公约数. 样例输入: 5 15样例输出:5 样例输入: 7 2样例输出:1 ...

  2. Java并发编程 ReentrantLock 源码分析

    ReentrantLock 一个可重入的互斥锁 Lock,它具有与使用 synchronized 方法和语句所访问的隐式监视器锁相同的一些基本行为和语义,但功能更强大. 这个类主要基于AQS(Abst ...

  3. systemd管理网络应用

    采用systemd-networkd管理网卡 主网卡eth0的配置文件/etc/systemd/network/20-eth0.network,静态配置时内容示例如下: [Match] Name=et ...

  4. [开发笔记]-ASP.NET项目在IIS上使用虚拟目录

    说一下我想要实现的效果: 假如我做一个图片展示类的网站,或者其他需要用户上传文件的网站,需要将用户上传的文件保存到一个Uploadfiles文件夹下,一般我们在做项目时用户上传的文件都是保存在网站项目 ...

  5. Intellij Idea搭建Spark开发环境

    在Spark高速入门指南 – Spark安装与基础使用中介绍了Spark的安装与配置.在那里还介绍了使用spark-submit提交应用.只是不能使用vim来开发Spark应用.放着IDE的方便不用. ...

  6. linux brctl command not found

    [root@localhost ~]# brctl-bash: brctl: command not found 解决方法: [root@localhost ~]# yum install bridg ...

  7. MVC教程七:扩展HtmlHelper方法

    在上一篇文章的最后,列出了一些常见的HtmlHelper的方法,这些都是ASP.NET MVC已经定义好的,如果我们想自己定义一个HtmlHelper方法可以吗?答案是肯定的,那么如何自定义一个Htm ...

  8. 1 php protocolbuffers安装

    安装工具 yum install autoconf yum install libtool 安装protoc编译器 # cd /root/soft/protobuf- autogen.sh : if ...

  9. mysql游标的使用

    这是一个游标的使用例子. 但是其中有几点需要注意,就是为什么要加入 declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tmpname = null;这 ...

  10. PCB设计与信号完整性

    之前在设计板卡时,只是听过相关的概念,但是未真正去研究关于SI相关的知识.将之前看过的一些资料整理如下: (1)信号完整性分析 与SI有关的因素:反射,串扰,辐射.反射是由于传输路径上的阻抗不匹配导致 ...