2014-11-03 38 views
2

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

+0

为什么不只是'分裂( '\\')'? – 2014-11-03 13:48:33

回答

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 
+1

看演示,它不是。你可以试试'[^ \\] * $'也http://regex101.com/r/nW5qZ0/4 – 2014-11-03 13:49:41

+0

它的工作原理。非常感谢您的及时回复。我很感激。 – 2014-11-03 13:52:55

+0

@GreenCode,提供的答案适用于您的情况。也许你的实现有问题吗? – 2014-11-03 13:53:02

4

我相信使用正则表达式是某种矫枉过正这里。您只需\分割字符串:

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

甚至更​​快:

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

无论如何,这是一个比上述更好的建议,因为如果用户的系统中的用户可以拥有以域为前缀的登录名,但也可以*不*,则它还会返回完整的用户名(如果它不是* Windows用户)。 :) – neminem 2017-10-04 16:51:13