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+)") Commented Jul 26, 2019 at 6:54

5 Answers 5

3

With no need of look behinds

gsub(".*\\[(\\d+).*","\\1",myString)
[1] "4577896"
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

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.

Comments

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"

Comments

1

An option using str_extract

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.