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

如何用R语言移除特定字符串前数字并合并重复空格?

Hey there! Let's fix your character vector cleaning issues step by step.

1. Remove the target number before "Votes."

Your original regex *. Votes didn't work because * is a quantifier in regex (matches the preceding element zero or more times), not a wildcard. That's why it ended up deleting everything—*. matches any character (.) zero or more times, paired with Votes it grabs the entire text up to the last occurrence of that string.

To target only numbers with thousand separators right before "Votes.", use this precise regex:

# Example text with the pattern
text <- "123,456 Votes. STATE QUESTION NO. 1 Amendment to Title 15 of the Ne..."

# Remove just the number (keep "Votes.")
cleaned_num <- gsub("\\d+(?:,\\d+)* (?=Votes\\.)", "", text)

Breakdown of the regex:

  • \\d+: Matches one or more digits
  • (?:,\\d+)*: Non-capturing group that matches zero or more instances of a comma followed by digits (handles thousand separators like 123,456 or 1,234,567)
  • (?=Votes\\.): Positive lookahead to ensure the number is immediately followed by "Votes." (avoids deleting other comma-containing numbers elsewhere)

If you actually want to remove the number and the " Votes." part (your original attempt hinted at this), adjust the regex to:

cleaned_num <- gsub("\\d+(?:,\\d+)* Votes\\.", "", text)
2. Merge duplicate spaces

Once you've removed the target number, collapse any multiple consecutive spaces into a single one with:

final_text <- gsub("\\s+", " ", cleaned_num)

\\s+ matches one or more whitespace characters (spaces, tabs, etc.), replacing them with a single space.

Full working example

Putting it all together:

# Sample input
text <- "987,654 Votes.   STATE QUESTION NO. 1   Amendment to Title 15 of the Ne..."

# Step 1: Remove the number before "Votes."
cleaned_num <- gsub("\\d+(?:,\\d+)* (?=Votes\\.)", "", text)
# Step 2: Clean up spaces
final_text <- gsub("\\s+", " ", cleaned_num)

# Check the result
cat(final_text)
# Output: Votes. STATE QUESTION NO. 1 Amendment to Title 15 of the Ne...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:13:41