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]*")

(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]*$")

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]*$")

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 <>
Reply-To: Lua list <>
To: Lua list <>
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
      return not nil

SDF Public Access UNIX System -