如何使用正则表达式截取指定用户名?附C#正则代码解惑
Hey there! Let's work through this summoner name extraction problem together—you’re already on the right track with regex, so let’s refine that and fix your code issue step by step.
1. Regex Matching Strategy
Your intuition is spot-on! We can target the two suffix patterns that follow summoner names:
- Pattern 1:
joined the lobby(note there's a typojoniedin your input—we’ll make the regex compatible with that) - Pattern 2:
:(colon plus space)
A clean way to do this is using a positive lookahead to capture only the Summoner+number part, ignoring the trailing junk. Here’s the regex:
Summoner\d+(?=( joined the lobby| jonied the lobby|:\s))
Summoner\d+: Matches any string starting withSummonerfollowed by one or more digits(?=...): Positive lookahead ensures the name is immediately followed by either the correct lobby join text, the typo version, or a colon-space combo—no extra characters get captured.
2. Fixing Your Code Error
The big issue in your original code is that list is a single string, but you’re using list.Select(x => ...) which iterates over each character in the string. That means your regex is running on individual letters, not the full summoner entries—definitely not what you want!
Here’s the corrected, working code:
var input = @"Summoner1 joined the lobby. Summoner2 jonied the lobby. Summoner3: Top Summoner4: ADC"; // Regex that handles both correct and typo'd lobby join text var summonerRegex = new Regex(@"Summoner\d+(?=( joined the lobby| jonied the lobby|:\s))"); // Grab all matching summoner names from the input var summonerMatches = summonerRegex.Matches(input); // Convert matches to strings and join with | var result = string.Join("|", summonerMatches.Cast<Match>().Select(m => m.Value)); // Output will be: Summoner1|Summoner2|Summoner3|Summoner4 Console.WriteLine(result);
3. Alternative: Split & Replace Approach
If you prefer a split-then-replace workflow (good for super consistent text formats), this works too:
var input = @"Summoner1 joined the lobby. Summoner2 jonied the lobby. Summoner3: Top Summoner4: ADC"; // Split the input into individual summoner entries var entries = input.Split(new[] { ". " }, StringSplitOptions.RemoveEmptyEntries); // For each entry, strip everything from the first space or colon onward var summoners = entries.Select(entry => Regex.Replace(entry, @"(\s|:\s).*", string.Empty)); var result = string.Join("|", summoners);
内容的提问来源于stack exchange,提问作者XHSKR

