Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

I'm trying to extract a number from a string.

And do something like [0-9]+ on the string "aaa12xxx" and get "12".

I thought it would be something like:

> grep("[0-9]+", "aaa12xxx", value=TRUE)

[1] "aaa12xxx"

And then I figured...

> sub("[0-9]+", "\\1", "aaa12xxx")

[1] "aaaxxx"

But I got some form of response doing:

> sub("[0-9]+", "ARGH!", "aaa12xxx")

[1] "aaaARGH!xxx"

There's a small detail I'm missing.

1 Answer

0 votes
by

To extract a regular expression match, you can use the str_extract function from the stringr package as follows:

str_extract("aaa12xxx", "[0-9]+")

[1] "12"

You can also use the str_locate function from the stringr package that locates the position of patterns in a string.i.e.,

 str_locate("aaa12xxx", "[0-9]+")

     start end

[1,]     4   5

Related questions

0 votes
1 answer
asked Nov 12, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...