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

求助:匹配仅含重复英文字母字符串的正则表达式

Fixing Regex for Repeated Same-Character Strings

Hey there! Let's get your regex sorted out. You want to match strings that consist only of the same repeated letter (A-Z or a-z)—like "aaa" or "BBB"—and your current pattern isn't quite hitting the mark. Let's break this down step by step.

What's Wrong With Your Current Regex?

Your current pattern: @"\b[a-z]{1}(.){1,}\b" has a couple of key issues:

  • [a-z] only matches lowercase letters, so it'll miss uppercase strings like "BBB".
  • (.) matches any character, not the same one as the first letter. This means it'll incorrectly match strings like "aab" or "a123".
  • {1} is redundant—by default, regex tokens match once, so you can omit these entirely.

The Correct Regex

To match strings made entirely of the same repeated letter, we use capturing groups and backreferences to ensure every character matches the first one. Here are two versions depending on your use case:

1. Match an Entire String (e.g., input is just "aaa")

Use this if you want to verify that the whole input string is made of repeated identical letters:

@"^([a-zA-Z])\1+$"

Let's break down each part:

  • ^ : Anchors the match to the start of the string.
  • ([a-zA-Z]) : Captures the first letter (covers both uppercase and lowercase) into a group (group 1).
  • \1+ : Matches the same character from group 1 at least once—so combined with the first character, this ensures there are 2+ identical letters.
  • $ : Anchors the match to the end of the string, ensuring no extra characters are present.

If you want to allow single-character strings (like "a" or "B"), change the + to *:

@"^([a-zA-Z])\1*$"

2. Match Such Strings as Words in a Larger Text

If you need to find these repeated-character strings within a longer sentence (e.g., finding "bbb" in "Look at bbb over there"), use word boundaries:

@"\b([a-zA-Z])\1+\b"

The \b ensures we only match whole words, not parts of longer strings (like the "aaa" in "aaabbb").

Example Usage in C#

Since you're using a verbatim string (@), here's how you'd implement this in code:

using System.Text.RegularExpressions;

// Check if an entire string is repeated identical letters
string testString = "BBB";
bool isValid = Regex.IsMatch(testString, @"^([a-zA-Z])\1+$");
// isValid will be true here

// Find all repeated-character words in a text
string text = "I saw aaa and BBB, but abc wasn't a match";
MatchCollection matches = Regex.Matches(text, @"\b([a-zA-Z])\1+\b");
// Matches will contain "aaa" and "BBB"

That should do exactly what you need! Let me know if you need further tweaks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:19:29