0

I have a string like this:

myString <- "[0.15][4577896]blahblahblahblahwhatever"

I need to extract the number between second brackets.

Currently I am trying to use this:

str_extract(myString, "\\]\\[(\\d+)")

But this gives me ][4577896

My desired result would be: 4577896

How could I achieve this?

1
  • Use lookbehind: stringr::str_extract(myString, "(?<=\\]\\[)(\\d+)")
    – Roland
    Commented Jul 26, 2019 at 6:54

5 Answers 5

3

With no need of look behinds

gsub(".*\\[(\\d+).*","\\1",myString)
[1] "4577896"
2

You can try this .(?<=\]\[)(\d+)

This is a demo.https://regex101.com/r/fvHW05/1

2

Here is another version with minimal or no regex

qdapRegex::ex_between_multiple(myString, "[", "]")[[2]]
#[1] "4577896"

It extracts all the substring between [ and ] and we select the value between second bracket. You can convert it into numeric or integer if needed.

1

You may use

^(?:[^\[\]]*\[[^\[\]]+\])[^\]\[]*\[([^\]\[]+).+

And replace this with the first captured group using gsub, see a demo on regex101.com. In base R:

myString <- "[0.15][4577896]blahblahblahblahwhatever"

pattern <- "^(?:[^\\[\\]]*\\[[^\\[\\]]+\\])[^\\]\\[]*\\[([^\\]\\[]+).+"
gsub(pattern, "\\1", myString, perl = T)
# [1] "4577896"
1

An option using str_extract

library(stringr)
str_extract(myString, "(?<=.\\[)([0-9]+)")
#[1] "4577896"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.