dancoup
dancoup

Reputation: 25

Detect Capital Letter in string package

I am a newbie and trying to detect the Letter C OR C/ OR C, in a string variable

x <- c("C", "C/", "C,", "C++", "C#", "Captain")

Desired output

True, True, True, False, False, False

Tried this but all capital letters are selected, excluding "Captain"

str_detect(x, "[C]")

Any help much appreciated.

Upvotes: 0

Views: 166

Answers (2)

dancoup
dancoup

Reputation: 25

thanks to you both. This code finally worked for me:

str_detect(input, "(^| )C[/,]?( |/|$)")

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

How about using grepl:

grepl("(^| )C[/,]?( |$)", input)
[1] "The C programming language"  "The C/ programming language"
[3] "The C, programming language"

Data:

input <- c("The C programming language",
    "The C/ programming language",
    "The C, programming language",
    "The C++ programming language",
    "The C# programming language",
    "Captain of all")

Demo

Edit:

Based on your updated expected output, maybe this is what you want:

grepl("^C[/,]?$", x)

Upvotes: 2

Related Questions