【问题标题】:Regex in ruby to enclose word before : with double quotesruby 中的正则表达式将之前的单词括起来:带双引号
【发布时间】:2014-09-24 09:35:59
【问题描述】:

我有一个字符串要转换成 json 字符串

下面是json的格式

               title: {
                    position: "bottom",
                    text: "Share of Internet Population Growth"
                },
                legend: {
                    visible: false
                },
                chartArea: {
                    background: ""
                },
                seriesDefaults: {
                    type: "donut",
                    startAngle: 150
                }

要将其转换为 JSON 字符串,我需要将 AnyKey: 替换为 "AnyKey":
我正在阅读有关 gsub 的信息。替换这种字符串的确切正则表达式是什么

提前致谢

【问题讨论】:

  • 您只需执行require 'json' 然后your_hash.to_json.. 就完成了!阅读this doco

标签: ruby regex json gsub


【解决方案1】:
(\w+)(?=:)

试试这个。查看演示。

http://regex101.com/r/zR2tR4/3

替换为"$1"

【讨论】:

  • 这并没有替换所有的键
  • 很多键遗漏了,例如title:,legend:,chartArea:
猜你喜欢
  • 2023-01-24
  • 2019-05-11
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多