Mayou
Mayou

Reputation: 8848

Extract a substring between two words from a string

I have the following string:

string = "asflkjsdhlkjsdhglk<body>Iwant\to+extr@ctth!sstr|ng<body>sdgdfsghsghsgh"

I would like to extract the string between the two <body> tags. The result I am looking for is:

substring = "<body>Iwant\to+extr@ctth!sstr|ng<body>"

Note that the substring between the two <body> tags can contain letters, numbers, punctuation and special characters.

Is there an easy way of doing this?

Upvotes: 7

Views: 5271

Answers (4)

Gardener
Gardener

Reputation: 2660

I believe that Matthew's and Steve's answers are both acceptable. Here is another solution:

string = "asflkjsdhlkjsdhglk<body>Iwant\to+extr@ctth!sstr|ng<body>sdgdfsghsghsgh"

regmatches(string, regexpr('<body>.+<body>', string))

output = sub(".*(<body>.+<body>).*", "\\1", string)

print (output)

Upvotes: 0

Steve P.
Steve P.

Reputation: 14709

regex = '<body>.+?<body>'

You want the non-greedy (.+?), so that it doesn't group as many <body> tags as possible.

If you're solely using a regex with no auxiliary functions, you're going to need a capturing group to extract what is required, ie:

regex = '(<body>.+?<body>)'

Upvotes: 6

Matthew Plourde
Matthew Plourde

Reputation: 44624

Here is the regular expression way:

regmatches(string, regexpr('<body>.+<body>', string))

Upvotes: 7

Stu
Stu

Reputation: 1653

strsplit() should help you:

>string = "asflkjsdhlkjsdhglk<body>Iwant\to+extr@ctth!sstr|ng<body>sdgdfsghsghsgh"
>x = strsplit(string, '<body>', fixed = FALSE, perl = FALSE, useBytes = FALSE)
[[1]]
[1] "asflkjsdhlkjsdhglk"         "Iwant\to+extr@ctth!sstr|ng" "sdgdfsghsghsgh"  
> x[[1]][2]
[1] "Iwant\to+extr@ctth!sstr|ng"

Of course, this gives you all three parts of the string and does not include the tag.

Upvotes: 2

Related Questions