需求C#正则表达式:匹配数字后紧跟单个字母X(排除连续X场景)
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 like1,15,999).[Xx]: Matches a single uppercaseXor lowercasex—use justXorxhere if you only care about one case.(?![Xx]): A negative lookahead assertion that ensures the character immediately after our matchedX/xis NOT anotherXorx. This is the key part that blocks sequences like12XXfrom 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

