I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis. For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python (How to add a missing closing parenthesis to a string in Python?). I have tried to modify the code to be used in R but to no avail. Can someone help me with this please?
I have tried modifying the original python solution as R doesn't recognise the "r" and "\" has been replaced by "\\" but this solution doesn't work properly and does not capture the string preceded before the bracket I would like to add:
text = "The dog walked (ABC in the park"
str_replace_all(text, '\\([A-Z] (?!\\))\\b', '\\)')
text
The python solution that works is as follows:
text = "The dog walked (ABC in the park"
text = re.sub(r'(\([A-Z] (?!\))\b)', r"\1)", text)
print(text)
CodePudding user response:
Try this
stringr::str_replace_all(text, '\\([A-Z] (?!\\))\\b', '\\0\\)')
- output
"The dog walked (ABC) in the park"
CodePudding user response:
You might also use gsub, and first use the word boundary and then the negative lookahead.
In the replacement use the first capture group followed by )
text = "The dog walked (ABC in the park"
gsub('(\\([A-Z] )\\b(?!\\))', '\\1\\)', text, perl=T)
Output
[1] "The dog walked (ABC) in the park"
CodePudding user response:
Not a one liner, but it does the trick and is (hopefully!) intuitive.
library(stringr)
add_brackets = function(text) {
brackets = str_extract(text, "\\([:alpha:] ") # finds the open bracket and any following letters
brackets_new = paste0(brackets, ")") # adds in the closing brackets
str_replace(text, paste0("\\", brackets), brackets_new) # replaces the unclosed string with the closed one
}
> add_brackets(text)
[1] "The dog walked (ABC) in the park"