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

需求C#正则表达式:匹配数字后紧跟单个字母X(排除连续X场景)

Solution for Matching Digits Followed by a Single X (C# Regex)

Got it, let's work through this regex problem step by step. You need to match sequences where digits are immediately followed by exactly one X (or x, based on your example), and exclude cases where multiple X's come after the digits (like 12XX).

The Regex Pattern

Here's the pattern that meets your requirements, with options for case sensitivity:

Case-Insensitive (matches both X and x)

\d+[Xx](?![Xx])

Case-Sensitive (only matches lowercase x)

\d+x(?!x)

Case-Sensitive (only matches uppercase X)

\d+X(?!X)

Breakdown of the Pattern

Let's break down the case-insensitive version to understand how it works:

  • \d+: Matches one or more consecutive digits (covers numbers like 1, 15, 999).
  • [Xx]: Matches a single uppercase X or lowercase x—use just X or x here if you only care about one case.
  • (?![Xx]): A negative lookahead assertion that ensures the character immediately after our matched X/x is NOT another X or x. This is the key part that blocks sequences like 12XX from being matched.

C# Code Example

Here's how you'd implement this in C# to test against your sample input:

using System;
using System.Text.RegularExpressions;

class RegexDemo
{
    static void Main()
    {
        string input = "This is ABC 15x DEF, 12XX should not match, 3X is valid, 4xx gets excluded";
        
        // Initialize regex with case-insensitive option
        Regex singleXRegex = new Regex(@"\d+[Xx](?![Xx])", RegexOptions.IgnoreCase);
        
        // Find all matches
        foreach (Match match in singleXRegex.Matches(input))
        {
            Console.WriteLine($"Matched: {match.Value}");
        }
    }
}

Output:

Matched: 15x
Matched: 3X

Optional: Ensure Full Word Boundaries

If you want to avoid matching digits that are part of a longer alphanumeric string (like abc12x), you can add word boundary assertions or negative lookbehinds to the pattern. For example:

(?<![a-zA-Z0-9])\d+[Xx](?![Xx])

The (?<![a-zA-Z0-9]) negative lookbehind ensures there's no letter or digit immediately before our number, so sequences like abc12x won't be matched.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:21:42