Jean
Jean

Reputation: 85

Remove any text inside square brackets in r

I would like to remove all the words inside square brackets as well as the brackets themselves. For example,

text = c('[Verse 1]', '[Verse 1: Dua Lipa]', '[Corus]', '[Corus: Ann Marie & Ed Sheeran]')

Like above, the length of words inside the bracket are not constant. So I need a function that can identify the position of [ and ] in order to erase all the words, numbers and symbols in between. Is there any function able to do that?

Upvotes: 1

Views: 1689

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may remove all substrings within square brackets using

gsub("\\[[^][]*]", "", text)

The pattern matches an open square bracket, then any zero or more chars other than square brackets, and then a close square bracket.

Upvotes: 5

Related Questions