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. 新浪微博 oauth2.0 redirect_uri_mismatch

    新浪微博开放平台出来很久了,现在才开始研究,貌似有点晚了.... 第一次折腾,总是出现这样那样的问题,即使照着别人成功的例子也是一样,这不,开始运行的时候,运行下面的例子,总是报error:redir ...

  2. angula学习

    入门 http://www.angularjs.cn/A004 http://www.cnblogs.com/whitewolf/p/angularjs-start.html http://www.n ...

  3. SpringBoot的文件下载

    SpringBoot的文件下载 2017年11月29日 10:32:20 阅读数:3907 SpringBoot的文件下载方法有很多,此处只记录使用Spring的Resource实现类FileSyst ...

  4. 2012Hulu校园招聘笔试题

    一.填空 侧重逻辑思维,没有语言.具体技术考察,大部分属于组合数学.算法.比较基本的知识点有二元树节点树.最小生成树.Hash函数常用方法等. 二.编程题 1.正整数剖分 2.AOE关键路径 3.二元 ...

  5. 安卓程序代写 网上程序代写[原]BluetoothSocket详解

    一. BluetoothSocket简介 1. 简介 客户端与服务端 : BluetoothSocket 和 BluetoothServerSocket 类似于Java中的套接字的 Socket 和 ...

  6. 1<<30 hashMap 中使用位移运算的意义

    static final int MAXIMUM_CAPACITY = 1 << 30; 计算过程已1<<30为例,首先把1转为二进制数字 0000 0000 0000 000 ...

  7. mysql insert exists || mysql 判断数据是否存在

    情景如下: "今日前端忽然说句, 我需要做个判断, 不能重复收藏, 我犹如颈有寒冰不寒而栗, 于是思考我该怎么做?为什么她都思考到了我没有思考到这是我的工作啊" 思考后得到三种解决 ...

  8. 第三百三十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—Scrapy启动文件的配置—xpath表达式

    第三百三十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—Scrapy启动文件的配置—xpath表达式 我们自定义一个main.py来作为启动文件 main.py #!/usr/bin/en ...

  9. JDBC Statement对象执行批量处理实例

    以下是使用Statement对象的批处理的典型步骤序列 - 使用createStatement()方法创建Statement对象. 使用setAutoCommit()将自动提交设置为false. 使用 ...

  10. CI框架 -- URI 路由

    一般情况下,一个 URL 字符串和它对应的控制器中类和方法是一一对应的关系. URL 中的每一段通常遵循下面的规则:example.com/class/function/id/ 但是有时候,你可能想改 ...