繁体   English   中英

试图构造一个正则表达式以匹配标记的用户名

[英]Trying to construct a regex to match tagged usernames

我正在尝试构建一个正则表达式(在C#中),以匹配标记的Facebook用户名(@ username1 @ user.name,@ user_name等)。 我认为Facebook用户名可以包含字母数字,破折号,句点和下划线字符。

这个仅与字母数字字符匹配,但是我需要一个也可以接受句点,破折号或下划线的字符:

MatchCollection results = Regex.Matches(text, "@\\w+");

任何帮助,非常感谢,谢谢!

尝试这个:

MatchCollection results = Regex.Matches(text, @"@[\w.-]+");

但是,这也将匹配电子邮件地址的域部分(因为根据您的规范,点是允许的字符)。 如果您不想这样做,则可以在断言后面添加一个负数,以确保@之前没有非空格字符:

MatchCollection results = Regex.Matches(text, @"(?<!\S)@[\w.-]+");

使用“完整列表”版本:

MatchCollection results = Regex.Matches(txt, @"(?:^|(?<=\s))@[a-zA-Z0-9_.-]+(?=\s|$)");

或简短版本( \\w = [a-zA-Z0-9_]

MatchCollection results = Regex.Matches(txt, @"(?:^|(?<=\s))@[\w.-]+(?=\s|$)");

您也可以这样做

List<string> tagedNames=Regex.Matches(text,@"(?<=(\s|^))@[\w.-]+")
                             .Cast<Match>()
                             .Select(x=>x.Value)
                             .ToList<string>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM