提取句子中的第一个字符串

时间:2019-09-27 08:59:49

标签: r

U有一个句子,我需要在其中提取第一个偶数词。例如

$(".leaflet-top" + ".leaflet-right").children().prepend('<div id="mapTitle" style="text-align: center;"><span style="font-size:16pt">Peta Bantuan Pemerintah</span></br><span style="font-size:12pt">Dinas Ketahanan Pangan Provinsi Riau</span></div><hr>');

对于上述句子,我需要提取“ This”,因为它是第一个偶数词

另一个例子是

  df <- ("This is not the sentence")

对于以上句子,我需要提取“ is”,因为它是第一个偶数词

1 个答案:

答案 0 :(得分:4)

我们可以编写一个函数来做到这一点。我们根据每个单词中的字符数对字符串进行拆分,然后返回第一个偶数单词。

extract_first_even_word <- function(text) {
   all_words <- strsplit(text, "\\s+")[[1]]
   all_words[which.max(nchar(all_words) %% 2 == 0)]
}
extract_first_even_word("This is not the sentence")
#[1] "This"

extract_first_even_word("She is not going anywhere")
#[1] "is"