You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除通用标点但保留否定式中的撇号?R语言字符串处理技术咨询

Solution for Preserving Negation Apostrophes While Removing General Punctuation in R

Got it, let's fix this regex issue so you can keep negation contractions like don't and wouldn't while stripping out possessive 's and general punctuation. The problem with your original regex is that it treats all apostrophes the same—we need to differentiate between apostrophes used in negations and those used in possessives or other punctuation.

Step-by-Step Solution

Here's a revised R code snippet that achieves exactly what you want:

library(stringr)

# Original input string
s <- c("I don't want to remove punctuation for negations. Instead, I want to remove only general punctuation. For example, keep I wouldn't like it but remove Inter's fan or Man city's fan.")

# Process the string
processed_s <- s %>%
  # 1. Remove possessive 's (skip if preceded by 'n' to avoid negations)
  # 2. Remove all general punctuation except apostrophes in negations
  str_replace_all("(?<!n)'s\\b|[^[:alnum:][:blank:]']", "") %>%
  # Clean up extra spaces created by punctuation removal
  str_squish()

# Output the result
cat(processed_s)

Explanation of the Regex

Let's break down the pattern to understand how it targets only the punctuation we want to remove:

  • (?<!n)'s\\b: This is a negative lookbehind assertion that matches possessive 's only if it's not preceded by the letter n. This ensures we never accidentally modify the n't in negations like wouldn't. The \\b marks a word boundary, so we only target 's at the end of nouns (e.g., Inter's, city's).
  • |[^[:alnum:][:blank:]']: The pipe (|) acts as an OR operator. This part matches any character that isn't a letter, number, space, or apostrophe—this eliminates commas, periods, and other general punctuation while leaving apostrophes in negations intact.
  • str_squish(): This function cleans up any extra spaces caused by removing punctuation (e.g., a period followed by a space becomes two spaces after removal, which this collapses to a single space).

Result

Running the code will output exactly your desired outcome:

"I don't want to remove punctuation for negations Instead I want to remove only general punctuation For example keep I wouldn't like it but remove Inter fan or Man city fan"

内容的提问来源于stack exchange,提问作者Rollo99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:02:45