1

文字列のデータ セットがあり、最初のコロンまでの部分文字列を抽出したいと考えています。以前、最初のコロンの後の部分だけを抽出する方法を尋ねてここに投稿しました: 最初のコロンで文字列を分割する 以下に、現在の問題を解決するためのいくつかの試みをリストします。

^[^:]+:保持したい部分と一致することはわかっていますが、その部分を抽出する方法がわかりません。

以下は、データセットの例と目的の結果です。

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 でのソリューションを好みます。

アドバイスありがとうございます。

4

3 に答える 3

6

「^[^:]+: が保持したい部分に一致することはわかっていますが、その部分を抽出する方法がわかりません。」

したがって、それを括弧で囲み、最後に「.+ $」を追加して、参照でサブを使用するだけです

sub("(^[^:]+:).+$", "\\1", vec)

 step1 <- sub("^([^:]+:).+$", "\\1", my.data2)
 step2 <- ifelse(grepl(":", step1), step1, 0)
 step2
#[1] "here is:"         "0"                "even:"            "0"               
#[5] "this text keeps:"

これらを別々のベクトル要素として、改行と一緒に貼り付けたいかどうかは明確ではありませんでした:

> step3 <- paste0(step2, collapse="\n")
> step3
[1] "here is:\n0\neven:\n0\nthis text keeps:"
> cat(step3)
here is:
0
even:
0
this text keeps:
于 2013-03-16T21:37:58.553 に答える
4

これはあなたが探しているものを生成するようです(ただし、コロンが含まれている行のビットのみを返します):

grep(":",gsub("(^[^:]+:).*$","\\1",my.data2 ),value=TRUE)
[1] "here is:"         "even:"            "this text keeps:"

これを入力していると、@DWinの回答が括弧を示唆しifelse、「0」も提供するのを見ました。

于 2013-03-16T21:50:39.703 に答える
2

を使用した別のあまりエレガントではないアプローチstrsplit:

x <- strsplit(my.data2, ":")
lens <- sapply(x, length)
y <- sapply(x, "[", 1)
y[lens==1] <- "0"
于 2013-03-17T00:13:02.993 に答える