Find CamelCase in a text in Ruby

1.6k Views Asked by At

Possible Duplicate:
Regular expression to identify CamelCased words

I'm trying to detect CamelCase in a text. In Rubular, my regex works fine, but doesn't seems to work in my script. My regex: http://rubular.com/r/fbeXAM69dX

My script: recognizers.rb

class NameRecognizer
def recognize(text)
  names = text.scan(NameRegex)
  th = TagHelper.new
  cc = th.isCamelCase?(names)
  cc ? (puts "Camel Case detected in '#{text}'") : (puts "No camel case in '#{text}'")
end
end

In another document, tag_helpers.rb

class TagHelper
def isCamelCase?(value)
  value = value.join(' ')
  finder = /([A-Z][a-z]+[a-z][A-Z][a-zA-Z]+)/
  value.match(finder) ? bool = true : bool = false
end
end

isCamelCase? worked but my regex detected something wrong, so I had to change, so I know the problem i my regex. If somebody have an idea, I'm kinda desperate.

EDIT: Here is my test

Recognizers::NameRecognizer.new.recognize("Camel Case")
Recognizers::NameRecognizer.new.recognize("NewsItalie")

I'm using Ruby 1.8.7

2

There are 2 best solutions below

0
On

As an addendum to Jason's answer, mainly because the comments compact everything:

The pattern:

r = /^[A-Z]\w+(?:[A-Z]\w+){1,}/x

Test data:

strs = ["Camelcase", "CamelCase", "camelCase", "camel case", "Camel Case", "Camel case", "CamelCaseLong"]

The code:

strs.each{|s| p s.scan( r ) }

Results:

[]
["CamelCase"]
[]
[]
[]
[]
["CamelCaseLong"]
7
On

Your regex should be /([A-Z][a-z]+[A-Z][a-zA-Z]+)/, the second [a-z] was unecessary and would exclude matches like "RoBot".