如何将字符串转换为挖掘可读格式rails?

How to convert string to dig readable format rails?

我在 rails 上使用 ruby。 我有一个字符串需要转换为挖掘可读格式

"search.user[0].user_id" convert this to [:search, :user,0, :user_id]

我正在尝试使用

"search.user[0].user_id".split('.').map(&:to_sym) which result to [:search, :user[0], :user_id]

如何进一步拆分数组索引,字符串可以将数组user[0]定位到任意位置。

要解析您的表达式,您可以使用:

"search.user[0].user_id".split(/]?\.|\[/).map{|k| k =~ /\A\d+\z/ && k.to_i || k.to_sym }
# => [:search, :user, 0, :user_id]

对于更通用的方法,还可以查看 jsonpath(解析更复杂的路径,例如 $.store.book[*](category,author)

您可以像下面这样转换字符串

str = "search.user[0].user_id" 
str.split(/[^a-zA-Z0-9_]/)
    .map { |s| s.empty? ? nil : (s.match?(/[0-9]+/)) ? s.to_i : s.to_sym }
    .compact

会return

[:search, :user, 0, :user_id]

这里有两种方法。

str = "search.user[0].user_id"

使用String#split

r1 = /\[|\]\.|\./
r2 = /\A\d+\z/
str.split(r1).map do |s|
  if s.match? r2
    s.to_i
  else
    s.to_sym
  end
end
  #=> [:search, :user, 0, :user_id] 

我们可以用free-spacing模式编写正则表达式,使它们自文档化。

r1 = /
     \[    # match '['
     |     # or
     \]\.  # match '].'
     |     # or
     \.    # match '.'
     /x    # invoke free-spacing regex definition mode
r2 = /
     \A    # match beginning of string
     \d+   # match one or more digits
     \z    # match end of string
     /x    # invoke free-spacing regex definition mode

使用String#scan

r1 = /
     [^\[\]\.] # match any character other than '[', ']' and '.'
     +         # perform above match one or more times
     /x        # invoke free-spacing regex definition mode

r2如上

str.scan(r1).map do |s|
  if s.match? r2
    s.to_i
  else
    s.to_sym
  end
end
  #=> [:search, :user, 0, :user_id]