Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

regex - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...