文字列のデータ セットがあり、最初のコロンまでの部分文字列を抽出したいと考えています。以前、最初のコロンの後の部分だけを抽出する方法を尋ねてここに投稿しました: 最初のコロンで文字列を分割する 以下に、現在の問題を解決するためのいくつかの試みをリストします。
^[^:]+:
保持したい部分と一致することはわかっていますが、その部分を抽出する方法がわかりません。
以下は、データセットの例と目的の結果です。
my.data <- "here is: some text
here is some more.
even: more text
still more text
this text keeps: going."
my.data2 <- readLines(textConnection(my.data))
desired.result <- "here is:
0
even:
0
this text keeps:"
desired.result2 <- readLines(textConnection(desired.result))
# Here are some of my attempts
# discards line 2 and 4 but does not extract portion from lines 1,3, and 5.
ifelse( my.data2 == gsub("^[^:]+:", "", my.data2), '', my.data2)
# returns the portion I do not want rather than the portion I do want
sub("^[^:]+:", "\\1", my.data2, perl=TRUE)
# returns an entire line if it contains a colon
grep("^[^:]+:", my.data2, value=TRUE)
# identifies which rows contain a match
regexpr("^[^:]+:", my.data2)
# my attempt at anchoring the right end instead of the left end
regexpr("[^:]+:$", my.data2)
この前の質問は、一致の反対を返すことに関するものです。上記にリンクされている以前の質問の解決策から始めた場合、R でこの解決策を実装する方法がわかりませんでした:正反対の正規表現
最近、正規表現を勉強するために RegexBuddy を入手しました。^[^:]+:
それが私が望むものと一致することを私が知っている方法です。その情報を使用して一致を抽出することができませんでした。
stringr
パッケージは承知しております。おそらくそれが役立つかもしれませんが、私はベース R でのソリューションを好みます。
アドバイスありがとうございます。