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. Eclipse 常用插件安装(最新更新:2016-12-06)

    . . . . . Eclipse 用得久了,不停地填充着各种好用的插件.由于我的版本较低,不支持插件导出功能(3.7以上支持),所以把各种体验比较好的插件记录在这里,以便将来全量升级Eclipse时 ...

  2. ListView@常用属性记录

    android:stackFromBottom="true" | "false" 默认false 说明:当listview加载完毕,显示最下面的内容,或者显示最 ...

  3. MyEclipse Maven Tomcat

    http://bbs.csdn.net/topics/390098011

  4. swing自定义border

    public class MyBorder extends AbstractBorder { private static final long serialVersionUID = 1L; priv ...

  5. Crystal Reports 版权疑问

    以前一直以为Crystal Reports是微软公司的产品,由于最近公司项目用到Crystal Reports,花了点时间研究了下它,才发现其实不然. 历史: 最开始的开发公司名为Crystal Se ...

  6. js 空数组是true还是false

    var arr = new Array(); // 或 var arr = []; 我们知道,初始化后,即使数组arr中没有元素,也是一个object. typeof arr; // "ob ...

  7. 【异常】IOException parsing XML document from class path resource [xxx.xml]

    1.IDEA导入项目运行出现异常 org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing ...

  8. PCL中分割_欧式分割(1)

    基于欧式距离的分割和基于区域生长的分割本质上都是用区分邻里关系远近来完成的.由于点云数据提供了更高维度的数据,故有很多信息可以提取获得.欧几里得算法使用邻居之间距离作为判定标准,而区域生长算法则利用了 ...

  9. TiKV 源码解析系列 - Raft 的优化

    本系列文章主要面向 TiKV 社区开发者,重点介绍 TiKV 的系统架构,源码结构,流程解析.目的是使得开发者阅读之后,能对 TiKV 项目有一个初步了解,更好的参与进入 TiKV 的开发中.本文是本 ...

  10. [hadoop读书笔记] 第一章 初识 Hadoop

    P3-P4: 目前遇见的问题很简单:硬盘容量不断提升,1TB的已成为主流,然而数据传输速度从1990年的4.4MB/s仅上升到当前约100MB/s 读取一个1TB的硬盘数据需要耗时至少2.5个小时.写 ...