Partial string extraction with stringr - getting NA - r

I'm trying to extract part of a string using stringr.
I'm aiming for the output to be E5_1_C33 and E5_1_C23, but instead I'm getting NA.
Any help would be appreciated!
library(stringr)
mystring <- c("can_ComplianceWHOInfrastructurePol_E5_1_C33","can_ComplianceWHOInfrastructurePol_E5_1_C23")
str_extract(mystring, "A\\d_\\d_B\\d\\d$")

slightly modified your line , as as need any letter not only A and B:
str_extract(mystring, "[A-z]\\d_\\d_[A-z]\\d\\d$")

Here's an R base approach using gsub
> gsub(".*(\\w{2}_\\w{1}_\\w{3})$", "\\1", mystring)
[1] "E5_1_C33" "E5_1_C23"

Related

Regex get string between intervals underscores

I've seen a lot of similar questions, but I wasn't able to get the desired output.
I have a string means_variab_textimput_x2_200.txt and I want to catch ONLY what is between the third and fourth underscores: textimput
I'm using R, stringr, I've tried many things, but none solved the issue:
my_string <- "means_variab_textimput_x2_200.txt"
str_extract(my_string, '[_]*[^_]*[_]*[^_]*[_]*[^_]*')
"means_variab_textimput"
str_extract(my_string, '^(?:([^_]+)_){4}')
"means_variab_textimput_x2_"
str_extract(my_string, '[_]*[^_]*[_]*[^_]*[_]*[^_]*\\.') ## the closer I got was this
"_textimput_x2_200."
Any ideas? Ps: I'm VERY new to Regex, so details would be much appreciated :)
additional question: can I also get only a "part" of the word? let's say, instead of textimput only text but without counting the words? It would be good to know both possibilities
this this one this one were helpful, but I couldn't get the final expected results. Thanks in advance.
stringr uses ICU based regular expressions. Therefore, an option would be to use regex lookarounds, but here the length is not fixed, thus (?<= wouldn't work. Another option is to either remove the substrings with str_remove or use str_replace to match and capture the third word which doesn't have the _ ([^_]+) and replace with the backreference (\\1) of the captured word
library(stringr)
str_replace(my_string, "^[^_]+_[^_]+_([^_]+)_.*", "\\1")
[1] "textimput"
If we need only the substring
str_replace(my_string, "^[^_]+_[^_]+_([^_]{4}).*", "\\1")
[1] "text"
In base R, it is easier with strsplit and get the third word with indexing
strsplit(my_string, "_")[[1]][3]
# [1] "textimput"
Or use perl = TRUE in regexpr
regmatches(my_string, regexpr("^([^_]+_){2}\\K[^_]+", my_string, perl = TRUE))
# [1] "textimput"
For the substring
regmatches(my_string, regexpr("^([^_]+_){2}\\K[^_]{4}", my_string, perl = TRUE))
[1] "text"
Following up on question asked in comment about restricting the size of the extracted word, this can easily be achieved using quantification. If, for example, you want to extract only the first 4 letters:
sub("[^_]+_[^_]+_([^_]{4}).*$", "\\1", my_string)
[1] "text"

Is there a way to split vectors in single character [duplicate]

Example:
string = "abc|3g"
function(string)
Solution: --> "abc" "3g"
Is there any idea how to split in the way as showed in the example?
strsplit(string,split='|', fixed=TRUE)
This is the possible answer. Other solutions?
A stringr option, using str_split_1, a shortcut for strsplit(...)[[1]].
library(stringr)
str_split_1(string, "\\|")

Converting character string to a vector [duplicate]

Example:
string = "abc|3g"
function(string)
Solution: --> "abc" "3g"
Is there any idea how to split in the way as showed in the example?
strsplit(string,split='|', fixed=TRUE)
This is the possible answer. Other solutions?
A stringr option, using str_split_1, a shortcut for strsplit(...)[[1]].
library(stringr)
str_split_1(string, "\\|")

Extract a part of string on a particular reference

I need to extract number that comes after "&r=" in the below link.
http://asdf.com/product/eyewear/eyeglasses?Brand[]=Allen%20Solly&r=472020&ck-source=google-adwords&ck-campaign=eyeglasses-cat-brand-broad&ck-adgroup=eyeglasses-dersdc-cat-brand-broad&keyword={keyword}&matchtype={matchtype}&network={network}&creative={creative}&adposition={adposition}
Here's what i tried
C has my link stored in.
sub(".*&r=", "",c)
"472020&ck-source=google-adwords&ck-campaign=eyeglasses-cat-brand-broad&ck-adgroup=eyeglasses-dersdc-cat-brand-broad&keyword={keyword}&matchtype={matchtype}&network={network}&creative={creative}&adposition={adposition}"
This only gives me whole after part of the string .
I only need the number i.e 472020 .
Any idea?
Here is how to get it using sub
sub(".*=(\\d+)&.*", "\\1", z)
#[1] "472020"
or
as.integer(sub(".*=(\\d+)&.*", "\\1", z))
#[1] 472020
For completeness sake, here it is with the base R regmatches/regexpr combo:
regmatches(z, regexpr("(?<=\\&r\\=)\\d+",z,perl=TRUE))
It uses the same Perl-flavoured regex as #akrun's stringr version. regexpr (or gregexpr if several matches of the same pattern are expected in the same string) matches the pattern, while regmatches extracts it (it is vectorized so several strings can be matched/extracted at once).
> as.integer(regmatches(z,regexpr("(?<=\\&r\\=)\\d+",z,perl=TRUE)))
#[1] 472020
We can use str_extract
library(stringr)
as.numeric(str_extract(z, "(?<=\\&r\\=)\\d+"))
#[1] 472020
If there are several matches use str_extract_all in place of str_extract

How to extract part of string using stringr?

I am learning about extracting string information using stringr library in R. Let's say I have a string LC_Cars_20160601_01.hdf5.rds. The numbers 01 before ".hdf5" indicate that it is for participant # 01. How can I extract this number? I have tried using str_extract but I don't know what should I provide in the pattern argument. Please guide.
One option is using gsub to remove all the elements that are not required
gsub(".*\\d+_|\\..*$", "", str1)
#[1] "01"
data
str1 <- "LC_Cars_20160601_01.hdf5.rds"

Resources