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

如何使用正则表达式仅移除字符串中与字母拼接或位于单词字符间的数字(保留日期及独立数字)

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, or 10th
  • Standalone numbers (e.g., 26 in "26 alphabets" or 5 as 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., the 123 in abc123 or a1b). 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., the 123 in 123abc). 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 by st, nd, rd, or th (ending at a word boundary)." This preserves values like 21st or 3rd.

Test Cases to Verify

Let's put this regex to the test with your examples and more scenarios:

Original TextAfter 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:02:37