在 Ruby 文本中查找驼峰式命名法

发布于 2024-12-26 11:32:56 字数 1136 浏览 1 评论 0原文

可能的重复:
识别 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南汐寒笙箫 2025-01-02 11:32:56

您的正则表达式应为 /([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".

眼趣 2025-01-02 11:32:56

作为 Jason 答案的附录,主要是因为注释压缩了所有内容:

模式:

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

测试数据:

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

代码:

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

结果:

[]
["CamelCase"]
[]
[]
[]
[]
["CamelCaseLong"]

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"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文