简体   繁体   English

正则表达式由目标字符串分割到某个字符

[英]Regex to split by a Targeted String up to a certain character

I have an LDAP Query I need to build the domain. 我有一个LDAP查询我需要构建域。

So, split by "DC=" up to a "comma" 因此,将“DC =”拆分为“逗号”

INPUT: INPUT:
LDAP://DC=SOMETHINGS,DC=ELSE,DC=NET\\account LDAP:// DC =出头,DC = ELSE,DC = NET \\帐户

RESULT: 结果:
SOMETHING.ELSE.NET SOMETHING.ELSE.NET

You can do it pretty simple using DC=(\\w*) regex pattern. 你可以使用DC=(\\w*)正则表达式模式非常简单地完成它。

var str = @"LDAP://DC=SOMETHINGS,DC=ELSE,DC=NET\account";
var result = String.Join(".", Regex.Matches(str, @"DC=(\w*)")
                                   .Cast<Match>()
                                   .Select(m => m.Groups[1].Value));

Without Regex you can do: 没有正则表达式,您可以:

string ldapStr = @"LDAP://DC=SOMETHINGS,DC=ELSE,DC=NET\account";
int startIndex = ldapStr.IndexOf("DC=");
int length = ldapStr.LastIndexOf("DC=") - startIndex;
string output = null;
if (startIndex >= 0 && length <= ldapStr.Length)
{
    string domainComponentStr = ldapStr.Substring(startIndex, length);
    output = String.Join(".",domainComponentStr.Split(new[] {"DC=", ","}, StringSplitOptions.RemoveEmptyEntries));
}

If you are always going to get the string in similar format than you can also do: 如果您总是以类似的格式获取字符串,那么您也可以:

string ldapStr = @"LDAP://DC=SOMETHINGS,DC=ELSE,DC=NET\account";
var outputStr = String.Join(".", ldapStr.Split(new[] {"DC=", ",","\\"}, StringSplitOptions.RemoveEmptyEntries)
                                .Skip(1)
                                .Take(3));

And you will get: 你会得到:

outputStr = "SOMETHINGS.ELSE.NET"

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

相关问题 在*字符正则表达式上分割字符串 - Split string on * character regex 除了某些字符组合之外的Split()字符串 - Split() string except for certain character combination 在某些字符计数后拆分字符串 - Split string after certain character count 使用释放字符和分隔符将正则表达式拆分为字符串 - split string with regex using a release character and separators 如何在不考虑字符长度的情况下拆分具有特定字符的字符串? - How to split a string with a certain character without considering the length of the character? 正则表达式使用前面带有特定字符的字符分割字符串 - Regex to split a string using a character preceded by a particular character 当字符串中的字符发生更改时,RegEx split / tokenize string - RegEx split/tokenize string when character within the string changes C#RegEx模式将字符串拆分为2个字符的子字符串 - C# RegEx Pattern to Split a String into 2 Character Substring 正则表达式匹配以某个字符结尾但不以另一个以中间空格开头的字符串 - Regex to match a string ending with a certain character but not beginning with another with intermediary whitespace C#:使用正则表达式替换某些字符,如果它们是字符串的第一个字符 - C#: Replace Certain Characters if they are the First Character of the String Using Regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM