簡體   English   中英

如何在C#中使用正則表達式從字符串中刪除所有不需要的字符?

[英]How to use regex in C# to remove all unwanted characters from a string?

我試過這里提供的解決方案Regex Code Review但我似乎無法讓它工作。 這與我正在處理的情況完全相同。 我還不熟悉正則表達式,但我想用它從字符串中刪除字符“CN =”,然后在字符串中的第一個逗號之后刪除所有內容。 例如,

CN = Joseph Rod,OU = LaptopUser,OU =用戶,DC =公司,DC =本地

約瑟夫羅德

碼:

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.AddRange(new DataColumn[5]
        {
            new DataColumn("givenName", typeof (string)),
            new DataColumn("sn", typeof (string)),
            new DataColumn("mail", typeof (string)),
            new DataColumn("department", typeof (string)),
            new DataColumn("manager", typeof (string))
        });

        using (var context = new PrincipalContext(ContextType.Domain, null))
        {
            using (var group = GroupPrincipal.FindByIdentity(context, "Users"))
            {
                var users = group.GetMembers(true);
                foreach (UserPrincipal user in users)
                {
                    DirectoryEntry de = user.GetUnderlyingObject() as DirectoryEntry;
                    dt.Rows.Add
                    (
                        Convert.ToString(de.Properties["givenName"].Value),
                        Convert.ToString(de.Properties["sn"].Value),
                        Convert.ToString(de.Properties["mail"].Value),
                        Convert.ToString(de.Properties["department"].Value),
                        Regex.Replace((Convert.ToString(de.Properties["manager"].Value)), @"CN=([^,]*),", "$1")
                    );
                }
                rgAdUsrs.DataSource = dt;
                rgAdUsrs.DataBind();
            }
        }
    }

然而,我的代碼只刪除了“CN =”和第一個逗號。 我需要從第一個逗號到右邊的所有內容都被刪除。

上述代碼的結果:

Joseph RodOU = LaptopUser,OU =用戶,DC =公司,DC =本地

如何修改正則表達式以刪除逗號右側的字符?

要刪除其余的行

CN=([^,]*),.*$

然后用$1替換。

正則表達式演示

但是,如前所述,您實際上並不需要正則表達式來實現這一點。 這將搜索第一之間的字符串=和第一,

Console.WriteLine(input.Substring(input.IndexOf("=") + 1, input.IndexOf(',') - (input.IndexOf("=") + 1)));

如果字符串始終以“CN =”開頭,則可以使用string.Substring()輕松獲取數據:

string input = "CN=Joseph Rod,OU=LaptopUser,OU=Users,DC=Company,DC=local";

// take a string starting at 3rd index, going to the first comma
Console.WriteLine(input.Substring(3, input.IndexOf(',') - 3));

//Output: "Joseph Rod"

如果字符串可以從任何東西開始,但始終堅持相同的模式,您可以使用Split()和一些LINQ:

string input = "OU=LaptopUser,CN=Joseph Rod,OU=Users,DC=Company,DC=local";
string[] splitInput = input.Split(',');
Console.WriteLine(splitInput.FirstOrDefault(x => x.StartsWith("CN="))?.Substring(3));

//Output: "Joseph Rod"

這里都是小提琴

這當然是假定合理的輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM