字符串中的Ruby override.index()来搜索字符或其HTML等价物



所以。。。我一直在使用所见即所得编辑器,并意识到他们偶尔会用该字符的十六进制代码替换某些字符,例如'&

如何重写String的索引方法,使其包含这些十六进制代码?

比如,somestring.index("'hello there")什么时候搜索''

注意:对于双引号,为了清楚起见,对单引号进行了转义。

进行这种字符串搜索最有效的方法是什么?有这样的东西已经内置了吗?

此外,由于我使用的是外部工具,所以我对事物的格式没有发言权。

解决方案:

 search_reg_exp = Regexp.escape(str).gsub(/(both|options|or|more)/, "(both|options|or|more)")
  long_str.index(search_reg_exp)

原始答案:

String#index不仅仅适用于单个字符,它可以用于任何长度的子字符串,并且您可以给它一个正则表达式,在这种情况下可能是最好的:

some_string    = "Russell's teapot"
another_string = "Russell's teapot"
apostrophe_expr = /'|'/
some_string.index apostrophe_expr
# => 7
another_string.index apostrophe_expr
# => 7

另一种选择是在开始操作字符串之前只解码HTML实体。有各种各样的宝石,包括html_helpers:

require 'html_helpers'
another_string = "Russell's teapot"
yet_another_string = HTML::EntityCoder.decode_entities another_string
# => "Russell's teapot"
yet_another_string.index "'"
# => 7
yet_another_string.index ?'  # bonus syntax tip--Ruby 1.9.1+
# => 7

最新更新