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

如何使用正则表达式移除句子中的单个字母及点号

Hey there! Let's get that regex sorted out for you. You're trying to remove single letters followed by a period (like B. or C.) from your medical text, and your current pattern isn't hitting the mark—let's fix that.

First, let's break down why your original regex [^A-Za-z]{0,}c[,.;\s]{0,} isn't working: that pattern is looking for any number of non-letter characters, followed by a lowercase c, then any number of punctuation or spaces. It doesn't target the single-letter-plus-period combinations you actually want to remove, so it's no surprise it's not doing anything.

The Working Regex Solution

For your specific text, the perfect pattern to use is:

\s[A-Za-z]\.\s

What each part does:

  • \s: Matches a single space (ensures the letter is standalone, not part of a longer word)
  • [A-Za-z]: Catches any single uppercase or lowercase letter
  • \.: Escaped period (since . is a wildcard in regex, we need to escape it to match a literal dot)
  • \s: Matches the space after the period

Replace any matches with a single space—this keeps the spacing between words natural after removing the X. tags.

Example Code (Python)

Here's how you'd implement this in practice:

import re

original_sentence = "Diagnosis: B. Prostate, Left Lateral Mid, Core Biopsy: - Prostatic adenocarcinoma, Gleason's score 3+3=6/10 - Single focus of carcinoma measures 0.5 mm (involves 1 of 1 core fragment and up to 5% of individual core volume) - Prostatic intraepithelial neoplasia (PIN high grade C. Prostate, Left Lateral Apex, Core Biopsy: - Prostatic "
cleaned_sentence = re.sub(r'\s[A-Za-z]\.\s', ' ', original_sentence)

print(cleaned_sentence)

Running this will output exactly the cleaned text you're expecting.

Handling Edge Cases (Optional)

If you ever need to cover scenarios where the X. is adjacent to punctuation (like B., or (C.), you can use a more flexible pattern:

(?:[:\(\s])[A-Za-z]\.(?:[\s,\)])

Just replace matches with the appropriate surrounding character (e.g., if you match (C. , replace with ( to keep the parenthesis intact). But for your current input, the first pattern works perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:27:30