【问题标题】:Regular expression to replace part of the expression in a json object [closed]正则表达式替换json对象中的部分表达式[关闭]
【发布时间】:2015-11-21 01:28:07
【问题描述】:

我正在尝试编写一个正则表达式来替换 json 文件对象中的一些有问题的字符。这是简短的 -DEMO

我能够编写 php 代码,但我无法在 R 中使用 str_replace 来实现它,因为它以 ,{ 字符开头。有关如何改进代码的任何建议?

library(stringr) 
json_file <- json_file<- '{"_id":{"$oid":"4f27779008d69a6dba0208f6"},"actor":{"gravatar_id":"92e5c51218f00220e0362c47b2a94b9a","id":NumberInt(228889),"login":"stefankendall","url":"https://api.github.com/users/stefankendall"},"created_at":"2012-01-31T05:09:37Z","id":"1515677813","org":{"url":"https://api.github.com/orgs/"},"payload":{"commits":[{"author":{"email":"skendall@skendalllaptop.(none)","name":"skendall"},"message":"Made test packages mimic app layout.","sha":"faf1b478f4d98202d4169b6d310812b14ad7f676","url":"https://api.github.com/repos/stefankendall/wendler531-webservices/commits/faf1b478f4d98202d4169b6d310812b14ad7f676"},{"author":{"email":"skendall@skendalllaptop.(none)","name":"skendall"},"message":"_id is now pulled out of \"get\" responses","sha":"d2087821e865ebebf9ff6e47cffb41dd16c6c871","url":"https://api.github.com/repos/stefankendall/wendler531-webservices/commits/d2087821e865ebebf9ff6e47cffb41dd16c6c871"}],"head":"d2087821e865ebebf9ff6e47cffb41dd16c6c871","push_id":NumberInt(59920001),"ref":"refs/heads/master","size":NumberInt(2)},"public":true,"repo":{"id":NumberInt(3186494),"name":"stefankendall/wendler531-webservices","url":"https://api.github.com/repos/stefankendall/wendler531-webservices"},"type":"PushEvent"}' 
str_replace_all(json_file, "\,{"author[^*]*],\\s*","")

【问题讨论】:

  • 我们应该从 json 文件中得到什么?
  • 你的正则表达式没有意义...
  • 它工作正常。这是正在工作的str_replace_all(json_file,',\\{\\"author[^\\*]*\\],\\s*',"")

标签: regex r stringr rjson


【解决方案1】:
  1. 您必须转义"s 或使用' 作为包装器而不是"
  2. 您必须在 R 中两次转义控制字符,即\\{\\^,尤其是\\\\,因为\ 是 R 中的控制字符! (每个\\ 都被\ 替换并传递给正则表达式解析器。
  3. 最终,\s 必须替换为 [:space:]

here

你必须使用str_replace_all(json_file,',\\{\\"author[^\\*]*\\],\\s*',"")(即使对我来说没有多大意义......)

【讨论】:

  • '\\\\,\{"author[^*]*],\\\\[:space:]*' 而不是 "\,{"author[^*]*],\\s*"
  • 您能提供解决方案吗?我对此并不陌生。
  • 您没有在问题中给出 json_file 的摘录。众所周知,当您自己没有编写正则表达式时,它们很难阅读。所以恐怕你必须尝试一下。
  • 我试过没有通过。这是我写的? str_replace_all(json_file ,'\\\\,\{"author[^*]*],\\\\[:space:]*',"")我收到以下错误错误:'\{' is an unrecognized escape in string started "'\\\\,\{"
  • json文件在demo中。我会尝试更新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
相关资源
最近更新 更多