从字符串中提取多个模式

时间:2020-02-06 12:24:23

标签: r dplyr

我有一个字符串:

a <- ":amount_min: !ruby/object:BigDecimal 18:0.8e2 :operator_min: gt :amount_max: !ruby/object:BigDecimal 18:0.1e4 :operator_max: lt"

我想将其恢复为:

a <- "min: 80, max:1000"

其中:0.8e2 = 800.1e4 = 1000

如何使用正则表达式来做到这一点?

3 个答案:

答案 0 :(得分:0)

一种解决方案,在数字前面使用冒号:

a <- ":amount_min: !ruby/object:BigDecimal 18:0.8e2 :operator_min: gt :amount_max: !ruby/object:BigDecimal 18:0.1e4 :operator_max: lt"

find_pos   <- gregexpr(pattern = ":[[:digit:]]", text = a)
get_string <- gsub(pattern = ":", "", substring(a,first=find_pos[[1]],last=find_pos[[1]]+5))
final      <- paste("min: ", as.numeric(get_string[1]), ", max: ", as.numeric(get_string[2]))

我也有一个硬编码的解决方案:

first_split <- strsplit(a, "BigDecimal 18:" )

min_val <- strsplit(first_split[[1]][2], ":")[[1]][1]
max_val <- strsplit(first_split[[1]][3], ":")[[1]][1]

final <- paste("min: ", as.numeric(min_val), ", max: ", as.numeric(max_val))

还有其他一些方法可以提取0.8e2,但始终可以用as.numeric来翻译该值

答案 1 :(得分:0)

这是尝试将简单的正则表达式与str_extract_all软件包中的stringr一起使用,

library(stringr)

paste(str_extract_all(a, 'amount_min|amount_max', simplify = TRUE), 
      as.numeric(str_extract_all(a, '[0-9]\\.[0-9]e[0-9]', simplify = TRUE)), 
      sep = ':', collapse = ', ')

#[1] "amount_min:80, amount_max:1000"

答案 2 :(得分:0)

这是使用[12,20,26,25,89,92,30,16] + JSONObject JA = new JSONObject(data); for (int i = 0; i < JA.length(); i++) { try { JSONObject jobj1 = (JSONObject) JA.get("today"); JSONObject jobj2 = jobj1.getJSONObject("Numbers"); JSONArray jarray_list = jobj2.getJSONArray("list"); Log.d(TAG, "Numbers = " + jarray_list); } catch (JSONException e) { e.printStackTrace(); } }

的基本R解决方案
regmatches

这样

gsub