Zach Fara
Zach Fara

Reputation: 101

Extract anything after a specific character (excluding the specific character)

How can I only get "C6:C7" from "s13$C6:C7" (anything after the \$ excluding the \$ itself)

str_extract("s13$C6:C7", '((\\$)=?).*')

this one still gives me the \$ at the beginning.

Upvotes: 1

Views: 47

Answers (3)

TarJae
TarJae

Reputation: 78917

We could also use str_replace:

.* 0 or more characters to account for the optional closing parenthesis, hyphen, and space characters

\\$ ends with $

library(stringr)
str_replace("s13$C6:C7", '.*\\$', '')
[1] "C6:C7"

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163217

You have a capture group around the dollar sign ((\\$)=?).* but if you want to extract it you can use the capture group for the second part of the pattern instead of the first part.

str_match("s13$C6:C7", '\\$(.*)')[2]

Output

[1] "C6:C7"

Note that .* can also match empty strings. If there should be at least a single char after the dollar sign and you want to for example match the allowed characters with a colon in between:

str_match("s13$C6:C7", '\\$([A-Z0-9]+(?::[A-Z0-9]+)*)$')[2]

See an R demo.

Upvotes: 2

akrun
akrun

Reputation: 886998

We can use regex lookaround (?<=) to match the characters (.*) that succeeds the $ sign

library(stringr)
str_extract("s13$C6:C7", '(?<=\\$).*')
[1] "C6:C7"

Or use str_remove to match the characters till the $ to remove those

str_remove("s13$C6:C7", '.*\\$')
[1] "C6:C7"

Upvotes: 2

Related Questions