【问题标题】:Lua pattern replace uppercase lettersLua 模式替换大写字母
【发布时间】:2015-04-11 02:40:45
【问题描述】:

我需要一个特殊的 Lua 模式,它将字符串中的所有大写字母替换为空格和相应的小写字母;

TestStringOne => test string one
this isA TestString => this is a test string

可以吗?

【问题讨论】:

    标签: lua pattern-matching uppercase lowercase lua-patterns


    【解决方案1】:

    假设只使用 ASCII,这可行:

    function lowercase(str)
      return (str:gsub("%u", function(c) return ' ' .. c:lower() end))
    end
    
    print(lowercase("TestStringOne"))
    print(lowercase("this isA TestString"))
    

    【讨论】:

    • %u 匹配大写; %l 小写 =)
    • @YuHao:你一定遗漏了一些东西(' ' .. ),因为这并没有考虑到增加的空间需求,实际上它与简单的 str:lower() 没有什么不同。
    【解决方案2】:
    function my(s)
      s = s:gsub('(%S)(%u)', '%1 %2'):lower()
      return s
    end
    
    print(my('TestStringOne'))              -->test string one
    print(my('this isA TestString'))        -->this is a test string
    

    【讨论】:

    • 我只是给你另一种可能性。他可以保留奖杯:)
    猜你喜欢
    • 2014-01-11
    • 1970-01-01
    • 2013-06-07
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多