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

Python中字符串替换优化:处理文本换行断词连字符问题

Fixing Hyphenated Word Splits (Including Line Breaks)

Got it, this is a super common text cleanup scenario—those annoying hyphenated words split either with a space (like evalu- ation) or a line break (like con-\ntribution) can be a real pain. While basic str.replace() works for one-off simple cases, regex lets you handle both scenarios in a single pass, which is way more efficient and robust.

Here's how to solve it:

The core idea is to target a hyphen followed by any kind of whitespace (spaces, line breaks, tabs—you name it) and replace that entire sequence with nothing, merging the split word back together seamlessly.

Example Code (Python):

import re

# Your sample text containing both split types
raw_text = """toward an emotionless evalu- ation of objectively gained
end up as a first rate con-
tribution, but that was not"""

# Use regex to match hyphens + any whitespace (one or more instances)
cleaned_text = re.sub(r'-\s+', '', raw_text)

print(cleaned_text)

Output:

toward an emotionless evaluation of objectively gained
end up as a first rate contribution, but that was not

Why this works:

  • The regex pattern -\s+ is designed to cover all your cases:
    • - matches the literal hyphen causing the split
    • \s+ matches one or more whitespace characters (this includes spaces, line breaks \n, tabs \t, and even multiple consecutive spaces)
  • re.sub() replaces every occurrence of this pattern with an empty string, effectively gluing the split parts of the word back into one.

Edge cases this covers:

  • Hyphen + single space (e.g., evalu- ation → evaluation)
  • Hyphen + line break (e.g., con-\ntribution → contribution)
  • Hyphen + multiple spaces/tabs (e.g., split- ting → splitting)

If you're working with other languages (like JavaScript), the same logic applies—just use the language's regex replace function. For example:

const rawText = `toward an emotionless evalu- ation of objectively gained
end up as a first rate con-
tribution, but that was not`;
const cleanedText = rawText.replace(/-\s+/g, '');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:48:53