简体   繁体   English

使用正则表达式提取用户名?

[英]Extract username with regex?

Extracting the username from this string? 从此字符串中提取用户名?

<title>[FirstName] [SecondName] (@[Username]) on [Site]</title>

I tried using regex but it gives me: 我尝试使用正则表达式,但它给了我:

Object reference not found exception. 找不到对象引用异常。

This is the code I use: 这是我使用的代码:

return Regex.Matches(title, @"\(([^)]*)\)").OfType<Match>().LastOrDefault().ToString();

Try following : 尝试以下操作:

            string input = "<title>[FirstName] [SecondName] (@[Username]) on [Site]</title>";

            string pattern = @"\[(?'value'[^\]]+)\]";

            MatchCollection matches = Regex.Matches(input, pattern);

            Console.WriteLine("User Name : '{0}'", matches[2].Groups["value"].Value);
            Console.ReadLine();

If you want to extract Username from <title>[FirstName] [SecondName] (@[Username]) on [Site]</title> you could capture in a group what is between (@[ and ]) by using a negated character class that matches not aa closing square bracket one or more times [^]+ : 如果要从<title>[FirstName] [SecondName] (@[Username]) on [Site]</title>提取Username ,则可以使用负字符在组中捕获(@[])之间的内容的是AA右方括号一次或多次不匹配[^]+

\\(@\\[([^\\]]+)\\]\\)

Demo 演示版

Or use a positive lookbehind the asserts what is on the left side is (@[ and a positive lookahead that asserts what is on the right side is ]) : 或使用肯定的后方断言来声明左侧的内容(@[和肯定的前瞻性来声明右侧的内容是])

(?<=\\(@\\[)[^]]+(?=\\]\\))

Demo 演示版

I just tested the code here and it works: 我刚刚在这里测试了代码,它可以工作:

var match = Regex.Matches("<title>[FirstName] [SecondName] (@[Username]) on [Site]</title>", @"\(([^)]*)\)")
                 .OfType<Match>()
                 .LastOrDefault()
                 .ToString();

The only difference with your code is that I'm not using title variable. 与您的代码的唯一区别是,我没有使用title变量。 So you title variable may be null , or empty or doesn't contains any match so you may end up with LastOrDefault().ToString(); 因此,您的title变量可能为null ,或者为空或不包含任何匹配项,因此您可能会以LastOrDefault().ToString();结尾LastOrDefault().ToString(); failing because you're calling ToString() on a null reference ( LastOrDefault returns null when you're dealing with an empty collection of reference types). 失败,因为您要在null引用上调用ToString() (当您处理空的引用类型集合时, LastOrDefault返回null )。

To fix the error just refactor your code like below: 要解决该错误,只需重构您的代码,如下所示:

var match = Regex.Matches("<title>[FirstName] [SecondName] (@[Username]) on [Site]</title>", @"\(([^)]*)\)")
                 .OfType<Match>()?
                 .LastOrDefault()?
                 .ToString();

The code after ? 后面的代码? character will be called only when the result is not null . 仅当结果不为null时,才调用该null

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

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