使用R正则表达式进行模式匹配问题

时间:2017-07-14 14:20:47

标签: r regex stringr

我尝试使用str_extract提取字符串。以下是字符串类型的一个小示例:

library(stringr)
gs<-"{\"type\":\"Polygon\",\"coordinates\":[[[1,2],[3,4],[5,6],[7,8]]]}"

s='\\{\\\"type\\\"*\\}'

str_extract(gs,s)

我希望打印出整个字符串(真正的字符串将包含更多此类型的字符,并且只应返回我在此指定的部分)。相反,我得到NA。我对任何关于我做错事的想法表示感谢。谢谢!

1 个答案:

答案 0 :(得分:0)

这样做你想要的吗?

gs<-"{\"type\":\"Polygon\",\"coordinates\":[[[1,2],[3,4],[5,6],[7,8]]]} I DO NOT WANT THIS {\"type\":\"Not a Polygon\",\"coordinates\":[[[1,2],[3,4],[5,6],[7,8]]]}"
s="\\{\"type\"(.*?)\\}"
result = str_match_all(gs,s)[[1]][,1]

为了测试,我添加了字符串'I DO NO WANT THIS',不应该返回,并添加了第二个类型为'not a polygon'的对象

它返回:

  

“{\” 类型\ “:\” 多边形\”,\ “坐标\”:[[[1,2],[3,4],[5,6],[7,8]]] }“
  “{\”type \“:\”不是   多边形\ “\ ”坐标\“:[[[1,2],[3,4],[5,6],[7,8]]]}”

所以只有要求的元素。希望这有帮助!