lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


You can use a different pattern and string.find rather than gsub

To find if the word contains a CamelCase string:

    function isCamelCase(str)
      return string.find(str,"%u%l+%u%l[%u%l]*")
    end

(Note that this returns nil if not found and a digit if it is)

To find out if the string contains ONLY a CamelCase word and nothing else, anchor the pattern's beginning and end:

    function isCamelCase(str)
      return string.find(str,"^%u%l+%u%l[%u%l]*$")
    end

To fix it so it returns true or false you can use a double not:

    function isCamelCase(str)
      return not not string.find(str,"^%u%l+%u%l[%u%l]*$")
    end

Note that it is very easy to modify the requirements. For example, you can allow digits at the end by changing the [%u%l] to %w.

  - Tom

On Mon, 3 Jan 2005, Alex Sandro Queiroz e Silva wrote:

Date: Mon, 03 Jan 2005 17:56:47 -0300
From: Alex Sandro Queiroz e Silva <ventonegro@ventonegro.org>
Reply-To: Lua list <lua@bazar2.conectiva.com.br>
To: Lua list <lua@bazar2.conectiva.com.br>
Subject: Testing for CamelCase

Hallo guys,

I've written the following function to test if a string is in camel case, because Lua patterns don't support modifiers on groupings. It works, but as I have little experience with text processing in Lua, I am posting it here to see if someone comes up with a better solution. Thanks!

-- checks if a string is in CamelCase
function isCamelCase(str)
  local count = 0
  local s = string.gsub(str, "(%u%l+)",
                      function(n) count = count + 1 return "" end)

  if count < 2 or s ~= "" then
      return nil
  else
      return not nil
  end
end

-alex



twrensch@sdf.lonestar.org
SDF Public Access UNIX System - http://sdf.lonestar.org