题
我想从C#中的登录ID中删除域/计算机信息。所以,我想制作“Domain \ me”和或“域\我”只是“我”。我总是可以检查是否存在,并使用它作为索引来启动子串...但我正在寻找更优雅和紧凑的东西。
更糟糕的情况:
int startIndex = 0;
int indexOfSlashesSingle = ResourceLoginName.IndexOf("\");
int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\");
if (indexOfSlashesSingle != -1)
startIndex = indexOfSlashesSingle;
else
startIndex = indexOfSlashesDouble;
string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1);
解决方案
当你拥有的只是一把锤子时,一切看起来都像钉子......
使用剃刀刀片----
using System;
using System.Text.RegularExpressions;
public class MyClass
{
public static void Main()
{
string domainUser = Regex.Replace("domain\\user",".*\\\\(.*)", "$1",RegexOptions.None);
Console.WriteLine(domainUser);
}
}
其他提示
你可以滥用Path类,因此:
string shortName = System.IO.Path.GetFileNameWithoutExtension(ResourceLoginName);
怎么样:
string shortName = ResourceLoginName.Split('\\')[1]
这对两者都有效,但对于命名组。
^(?<domain>.*)\\(?<username>.*)|(?<username>[^\@]*)@(?<domain>.*)?$
我总是这样做:
string[] domainuser;
string Auth_User = Request.ServerVariables["AUTH_USER"].ToString().ToLower();
domainuser = Auth_User.Split('\\');
现在你可以看一下domainuser.Length,看看有多少个部分,域名为domainuser [0],域名用户[1]为用户名。
string theString = "domain\\me";
theString = theString.Split(new char[] { '\\' })[theString.Split(new char[] { '\\' }).Length - 1];
这适用于两个有效的域登录:
var regex = @"^(.*\\)?([^\@]*)(@.*)?<*>quot;;
var user = Regex.Replace("domain\\user", regex, "$2", RegexOptions.None);
user = Regex.Replace("user@domain.com", regex, "$2", RegexOptions.None);
小猪支持Derek Smalls答案......
Regex.Replace(User.Identity.Name,@"^(?<domain>.*)\\(?<username>.*)|(?<username>[^\@]*)@(?<domain>.*)?<*>quot;, "${username}", RegexOptions.None)
为我工作。
不隶属于 StackOverflow