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

如何使用正则表达式截取指定用户名?附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.

Summoner Name Extraction Solution

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 typo jonied in 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 with Summoner followed 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:07:37