如何修改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
相关产品推荐
相关产品推荐

