Replace string before parentheses

Viewed 36

I am trying to replace numbers before parentheses:

string <- "1234556 (789)"
    
sub("*.\\(*.", "foo", string)  

[1] "foo34556 (789)"

I am looking for this result:

 result <- "foo (789)"
3 Answers

Try this?

> sub("^[^( ]+", "foo", string)
[1] "foo (789)"

This should be the correct regex

sub("[0-9]+", "foo", string)  

"foo (789)"

To replace numbers before the parenthesis, you can match 1 or more digits (which should be replaced), and capture the optional spaces including from an opening till closing parenthesis in group 1.

In the replacement use foo followed by the group 1 value.

string <- "1234556 (789)"
sub("\\d+(\\s*\\([^()]*\\))", "foo\\1", string)

Output

[1] "foo (789)"

See an R demo and a regex demo for the match and group value.

Related