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)"
CodePudding user response:
Try this?
> sub("^[^( ] ", "foo", string)
[1] "foo (789)"
CodePudding user response:
This should be the correct regex
sub("[0-9] ", "foo", string)
"foo (789)"
CodePudding user response:
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.