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

如何用正则表达式匹配字符串中任意位置的恰好两个相同字符?

Hey there! I see the issue with your regex—it's only catching consecutive duplicate characters (like the two 0s in '1002'), but you want to match strings where a character appears exactly twice, even if they're spread out (like the 0s in '1030'). Let's fix this step by step.

Why Your Current Code Fails

The regex 0{2} specifically looks for two consecutive 0s, which is why it misses cases like '1030' where the duplicate characters are separated by other characters. We need a pattern that checks for any character appearing exactly twice anywhere in the string.

Solution 1: Regex for "At Least One Character Appears Exactly Twice"

If your goal is to match any string where at least one character shows up exactly twice (and no character shows up three or more times), use this regex:

import re

def matches_exactly_two_duplicates(s):
    # Regex breakdown:
    # ^(?!.*(.).*\1.*\1) → Ensure no character appears 3+ times
    # (?=.*(.).*\2) → Ensure at least one character appears twice
    # .* → Match the rest of the string
    pattern = r'^(?!.*(.).*\1.*\1)(?=.*(.).*\2).*$'
    return bool(re.search(pattern, s))

# Test cases
print(matches_exactly_two_duplicates('1030'))  # True (0 appears twice)
print(matches_exactly_two_duplicates('4003'))  # True (0 appears twice)
print(matches_exactly_two_duplicates('1002'))  # True (0 appears twice)
print(matches_exactly_two_duplicates('1112'))  # False (1 appears three times)
print(matches_exactly_two_duplicates('1234'))  # False (no duplicates)
print(matches_exactly_two_duplicates('1122'))  # True (both 1 and 2 appear twice)

Solution 2: Strict Match (Only One Pair of Duplicates, Rest Unique)

If you need to exclude cases like '1122' (where two different characters each appear twice), and only want strings with exactly one pair of duplicates and all other characters unique, using Python's Counter is more straightforward than a complex regex:

from collections import Counter

def has_exactly_one_unique_pair(s):
    char_counts = Counter(s)
    # Check: exactly one character appears twice, and no character appears more than twice
    duplicate_count = sum(1 for count in char_counts.values() if count == 2)
    no_triplicates = all(count <= 2 for count in char_counts.values())
    return duplicate_count == 1 and no_triplicates

# Test cases
print(has_exactly_one_unique_pair('1030'))  # True
print(has_exactly_one_unique_pair('4003'))  # True
print(has_exactly_one_unique_pair('1122'))  # False (two pairs of duplicates)
print(has_exactly_one_unique_pair('1112'))  # False (triplicate character)

This approach is easier to read and maintain, especially if your requirements evolve later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:22:19