字符串模式查找字符

本文关键字:字符 查找 模式 字符串 | 更新日期: 2023-09-27 18:02:15

我的文本文件的格式是这样的;

ID: 300000000 NAME: 3rd: Ellin Forest: Altaire Camp
ID: 300000100 NAME: 3rd: Altaire Camp: Small Forest
ID: 687000000 NAME: Gacha_GL: Gacha: Gachapon
ID: 682000000 NAME: HalloweenGL: Phantom Forest: Haunted House

字符串模式查找字符

在正则表达式中包含缓冲区部分:

ID: (?<id>'d*) NAME: (?<buffer>.*?:) (?<name>.*)
string name =  match.Groups["name"].Value; // "Gacha_GL: Gacha: Gachapon";
string correctName = String.Join(": ", name.Split(new[]{": "}, StringSplitOptions.None).Skip(1).ToArray());

您可以修改您的Regex以直接通过

获得此输出
string pattern = @"ID: (?<id>'d*) NAME:(?<prename>.*?:)(?<name>.*)";

但是我不确定你是否需要使用原来的Regex,在这种情况下,你可以做到这一点,而不破坏你现有的Regex如下

void PopulateWith(string rawText)
{
    string pattern = @"ID: (?<id>'d*) NAME: (?<name>.*)";
    foreach (Match match in Regex.Matches(rawText, pattern))
    {
        int id = int.Parse(match.Groups["id"].Value);
        string name = match.Groups["name"].Value;
        name = String.Join(": ", 
            name.Split(new[]{": "}, StringSplitOptions.None).Skip(1).ToArray());
    }
}

它们都产生所需的输出:

Gacha: Gachapon