正则表达式优化求助:移除缺失括号的句末引用内容
Got it, let's sort out this regex problem! Your original pattern works for single sentences because it doesn't have to worry about crossing sentence boundaries, but when you use it on multi-sentence text like mystring2, the greedy .* matches everything from the first "e.g.," all the way to the last year in the entire string—way more than you want to delete.
Here's the fixed regex that only targets the unparenthesized citation block at the end of individual sentences:
# Updated gsub call for mystring2 gsub(x = mystring2, pattern = "ﰃe\\.g\\.,[^.]*?[0-9]{4}ﰀ(?=\\.)", replacement = "", perl = TRUE)
Let me break down how this fixes the issue:
ﰃ: Catches that unusual opening bracket from your original texte\\.g\\.,: Explicitly matches the start of the citation prefix[^.]*?: Uses a non-greedy match for any character that isn't a period. This is key—it stops the match from crossing into the next sentence (since sentences end with periods)[0-9]{4}: Grabs the final year in the citation sequenceﰀ: Catches the unusual closing bracket(?=\\.): A positive lookahead that ensures the entire citation block is immediately followed by a period, so we only target citations at the end of a sentence
When you run this on mystring2, it will only remove the problematic citation at the end of the first sentence, leaving all the subsequent sentences completely intact—exactly what you need.
内容的提问来源于stack exchange,提问作者jazzurro

