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

如何修改Python正则表达式,移除非单词字符同时保留单引号?

Hey there! Let's fix that regex so it keeps single quotes while stripping out other non-alphabet characters.

First, a tiny heads-up: Your original regex has a small typo—there's an extra closing bracket ] at the end. It should be [^A-Za-z] instead of [^A-Za-z]].

To preserve single quotes, all you need to do is add the single quote ' to the set of allowed characters in your negated character class. Here's the modified code:

import re

original_string = "Queen's son is sleeping, but he will wake up."
processed_string = re.sub("[^A-Za-z']", ' ', original_string).lower()
# Remove .lower() if you want to keep original capitalization
print(processed_string)

Running this will give you exactly the output you're looking for:

queen's son is sleeping but he will wake up

Quick breakdown of how it works:

  • The regex [^A-Za-z'] matches any character that isn't an uppercase letter, lowercase letter, or single quote. We replace all those matches with a space.
  • The .lower() call converts the entire string to lowercase (like turning "Queen" to "queen")—if you want to keep the original capitalization, just remove that part entirely.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:26:51