如何在R中第一次出现逗号之前删除所有内容

我正在尝试删除文本,直到包含一个或多个逗号的字符串中的第一个逗号为止。出于某种原因,我发现这总是删除所有字符串的最后一个逗号之前的所有内容。

字符串看起来像:

OCR - (some text), Variant - (some text), Bad Subtype - (some text)

我的正则表达式正在返回:

Bad Subtype - (some text)

当所需的输出是:

Variant - (some text), Bad Subtype - (some text)

Variant 不能保证排在第二位。

#select all strings beginning with OCR in the column Tags
clean<- subset(all, grepl("^OCR", all$Tags)
#trim the OCR text up to the first comma, and store in a new column called Tag
    clean$Tag<- gsub(".*,", "", clean$Tag) 

或者

clean$Tag <- gsub(".*\,", "", clean$Tag)

或者

clean$Tag<- sub(".*,", "", clean$Tag)

等等..

回答

一个选项trimwsfrombase R

trimws(x, whitespace = "^[^,]+,\s*")

-输出

#[1] "Variant - (some text), Bad Subtype - (some text) and my regex is returning: Bad Subtype - (some text) when the desired output is: Variant - (some text), Bad Subtype - (some text)"

数据

x <- "OCR - (some text), Variant - (some text), Bad Subtype - (some text) and my regex is returning: Bad Subtype - (some text) when the desired output is: Variant - (some text), Bad Subtype - (some text)"


以上是如何在R中第一次出现逗号之前删除所有内容的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>