Klllmmm
Klllmmm

Reputation: 136

Find & replace a character in a particular position

Comment
(apple (a) 100)
(orange 50)



Comment1
apple (a) 100
orange 50

I need to replace the starting open parenthesis & ending closing parenthesis with none using r.

Sample of my data is in "comment" field. My expected output is in "Comment1" field.

Upvotes: 1

Views: 67

Answers (1)

akrun
akrun

Reputation: 887851

We can use gsub to match the brackets at the beginning (^\\() or (|) at the end (\\)$) and replace it with "".

gsub("^\\(|\\)$", "", Comment)
#[1] "apple (a) 100" "orange 50"    

Or if it is based on position, we can place the characters that are needed in a capture group i.e. inside the brackets ((.*)) and replace it with the backreference (\\1).

sub(".(.*).", "\\1", Comment)
#[1] "apple (a) 100" "orange 50" 

Or with substring

substring(Comment, 2, nchar(Comment)-1)
#[1] "apple (a) 100" "orange 50"    

data

Comment <- c("(apple (a) 100)","(orange 50)")

Upvotes: 4

Related Questions