在 Ruby 文本中查找驼峰式命名法
可能的重复:
识别 CamelCased 单词的正则表达式
我正在尝试检测文本中的 CamelCase 。在 Rubular 中,我的正则表达式工作正常,但在我的脚本中似乎不起作用。 我的正则表达式: http://rubular.com/r/fbeXAM69dX
我的脚本: 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
在另一个文件中,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
是CamelCase?有效,但我的正则表达式检测到有问题,所以我必须更改,所以我知道我的正则表达式有问题。如果有人有想法,我有点绝望。
编辑:这是我
Recognizers::NameRecognizer.new.recognize("Camel Case")
Recognizers::NameRecognizer.new.recognize("NewsItalie")
使用 Ruby 1.8.7 的测试
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的正则表达式应为
/([AZ][az]+[AZ][a-zA-Z]+)/
,第二个 [az] 是不必要的,会排除“RoBot”等匹配项。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".作为 Jason 答案的附录,主要是因为注释压缩了所有内容:
模式:
测试数据:
代码:
结果:
As an addendum to Jason's answer, mainly because the comments compact everything:
The pattern:
Test data:
The code:
Results: