R Get Characters Between Brackets In a String

I want to get characters between brackets.

Here is an example of my data.

[ADAM SMITH] update status of [34BND001] . Status [AVAILABLE => OUT_OF_SERVICE (dirty)]

Wanted output: 34BND001

Thank you,

Upvotes: 0

Views: 37

Answers (1)

akrun
akrun

Reputation: 886978

We can use str_extract and match it with regex. Here, we use a regex lookaround ((?<=\\[) that matches the [ followed by one or more digits (\\d+) and characters that are not a ] ([^]]+)

library(stringr)
str_extract(str1, "(?<=\\[)\\d+[^]]+")
#[1] "34BND001"

data

str1 <- "[ADAM SMITH] update status of [34BND001] . Status [AVAILABLE => OUT_OF_SERVICE (dirty)]"

To known this expressions you can search further about regex (regular expressions)

Upvotes: 2

Related Questions