检索整个字符串和选定的字符串。
all_text <- svalue(textwin, index=0)
selected_text <- svalue(textwin, index=0, drop = TRUE)
然后使用regexpr查找所选子字符串的索引。
rx_match <- regexpr(selected_text, all_text, fixed = TRUE)
用其他东西替换那个子字符串。
substring(
all_text,
rx_match,
rx_match + attr(rx_match, "match.length") - 1
) <- "monkey"
更新文本框。
svalue(textwin) <- all_text
B 计划:使用index = 1 操作来自svalue 的返回值。这几乎是正确的,但我认为gWidgets 中存在一个错误,导致它无法正常工作。
# Get the index of the lines/character positions to start and finish
i <- format(svalue(textwin, index = 1, drop = TRUE), digits = 3)
i <- sapply(strsplit(i, "\\."), as.numeric)
# Get all the text as a character vector
all_text <- svalue(textwin, index=0)
all_text <- strsplit(all_text, "\n")[[1]]
# Replace the selected portion
replacement <- "monkey"
if(i[1, 1] == i[1, 2])
{
svalue(textwin) <- substring(all_text[i[1, 1]], i[2, 1], i[2, 2])
} else
{
all_text[i[1, 1]] <- paste0(
substring(all_text[i[1, 1]], 1, i[2, 1]),
replacement,
substring(all_text[i[1, 2]], 1, i[2, 2])
)
svalue(textwin) <- all_text[-((i[1, 1] + 1):(i[1, 2]))]
}
最大的问题是调用format 将索引号转换为字符串。与两位数的位置相比,它在个位数的位置上表现不佳。我相当确定这是getMethod(.svalue, signature("gTexttcltk", "guiWidgetsToolkittcltk")) 中的一个错误(尽管其他工具包中也可能存在问题)。