RegEx(?='\\')。* $ - 尝试从域\用户名获取用户名

时间:2014-11-03 13:45:46

标签: .net regex

我有一个像domainA\userNamePaul这样的字符串。我尝试了这个正则表达式(?='\\').*$,但输出与输入相同。我需要获取没有域名的用户名。知道我做错了什么。

2 个答案:

答案 0 :(得分:4)

我认为使用正则表达式在某种程度上是一种矫枉过正。您可以简单地按\分割字符串:

string identity = "DOMAIN\\USER";
string user = identity.Split('\\').Last();

甚至更快:

string user = identity.Substring(identity.IndexOf('\\') + 1);

答案 1 :(得分:3)

您需要使用Positive lookbehind

(?<=\\).*$

DEMO

<强>解释

(?<=                     look behind to see if there is:
  \\                       '\'
)                        end of look-behind
.*                       any character except \n (0 or more times)
$                        before an optional \n, and the end of the
                         string