Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Regex可以获取以@开头的所有内容,并删除任何非包含字符后的所有内容_C#_Regex - Fatal编程技术网

C# Regex可以获取以@开头的所有内容,并删除任何非包含字符后的所有内容

C# Regex可以获取以@开头的所有内容,并删除任何非包含字符后的所有内容,c#,regex,C#,Regex,我有以下资料: Regex RgxUrl = new Regex("[^a-zA-Z0-9-_]"); foreach (var item in source.Split(' ').Where(s => s.StartsWith("@"))) { var mention = item.Replace("@", ""); mention = RgxUrl.Replace(mention, "");

我有以下资料:

        Regex RgxUrl = new Regex("[^a-zA-Z0-9-_]");
        foreach (var item in source.Split(' ').Where(s => s.StartsWith("@")))
        {
            var mention = item.Replace("@", "");
            mention = RgxUrl.Replace(mention, "");
            usernames.Add(mention);
        }
当前输入>输出

  • @鱼和薯条是@good
  • @鱼和薯条以及@Mary's啤酒是@good
    玛丽
所需输入>输出

  • @鱼和薯条是@good
  • @鱼、薯条和@Mary's啤酒是@good
    玛丽

这里的关键是删除任何在冒犯角色之后的内容。如何实现这一点?

将字符串拆分为空格,检查块是否以
@
开头,如果是,则删除字符串中的所有
@
符号,然后使用正则表达式删除字符串中的所有非字母数字、
-
字符,然后将其添加到列表中

您可以使用单个正则表达式执行此操作:

var res = Regex.Matches(source, @"(?<!\S)@([a-zA-Z0-9-_]+)")
    .Cast<Match>()
    .Select(m=>m.Groups[1].Value)
    .ToList();
Console.WriteLine(string.Join("; ", res)); // demo
usernames.AddRange(res); // in your code

var res=Regex.Matches(source,@)(?您当前的代码输出
fish
Marys
good
。也许,您所需要的只是
Regex.Matches(source,@)(
Regex.Matches)(输入,@)(?我看不出您在代码中的什么地方更改了大小写。@WiktorStribiżew Typo-case无所谓。非常感谢。如果您需要将大小写调低,只需使用
。选择(m=>m.Groups[1].Value.ToLower())
谢谢!ssss