如何使用正则表达式仅移除字符串中与字母拼接或位于单词字符间的数字(保留日期及独立数字)
Fixing Your Regex to Target Only Digits Attached to Letters
Great question! Your current regex re.sub(r'[0-9]+', '', newString) is too broad—it yanks out every digit it finds, regardless of context. Let's tweak it to only remove digits that are directly attached to letters (either before, after, or sandwiched between them), while preserving:
- Date ordinal numbers like
21st,3rd, or10th - Standalone numbers (e.g.,
26in "26 alphabets" or5as a standalone value)
The Revised Regex
Here's the pattern you need:
import re newString = re.sub(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])(?!(?:st|nd|rd|th)\b)', '', newString)
Breakdown of the Pattern
Let's break down each part to understand how it works:
(?<=[a-zA-Z])\d+: Matches digits that come right after a letter (e.g., the123inabc123ora1b). The(?<=...)is a positive lookbehind—only match digits if a letter precedes them.|: Acts as an "or" operator to combine two matching rules.\d+(?=[a-zA-Z])(?!(?:st|nd|rd|th)\b):\d+(?=[a-zA-Z])matches digits that come right before a letter (e.g., the123in123abc). The(?=...)is a positive lookahead—only match digits if a letter follows them.(?!(?:st|nd|rd|th)\b)is a negative lookahead that excludes date ordinals. It says: "Don't match these digits if they're immediately followed byst,nd,rd, orth(ending at a word boundary)." This preserves values like21stor3rd.
Test Cases to Verify
Let's put this regex to the test with your examples and more scenarios:
| Original Text | After Regex Replacement |
|---|---|
"abc123def" | "abcdef" |
"123abc" | "abc" |
"21st of October" | "21st of October" |
"26 alphabets" | "26 alphabets" |
"a1b2c3" | "abc" |
"5 is a standalone number" | "5 is a standalone number" |
"hello 789 world" | "hello 789 world" |
"123test456" | "test" |
"3rd floor" | "3rd floor" |
Edge Case Adjustment (If Needed)
If you also need to handle underscores (since \w includes underscores), replace [a-zA-Z] with [a-zA-Z_] in the pattern. But based on your question, focusing on letters should be sufficient.
内容的提问来源于stack exchange,提问作者Namra Rehman
相关产品推荐
相关产品推荐

