在CN=
之后直接分割该字符串以便将第一个和最后一个名称存储在单独字段中的最佳方法如下所示?用多个分隔符分割Java字符串
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String firstName"Paul"
String lastName="Sebula"
在CN=
之后直接分割该字符串以便将第一个和最后一个名称存储在单独字段中的最佳方法如下所示?用多个分隔符分割Java字符串
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String firstName"Paul"
String lastName="Sebula"
您可以使用split
:
String distinguisedName = "CN=Paul Sebula,OU=BAE,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=baesystems,DC=com";
String[] names = distinguisedName.split(",")[0].split("=")[1].split(" ");
String firstName = names[0];
String lastName= names.length > 2 ? names[names.length-1] : names[1];
System.out.println(firstName + " " + lastName);
见IDEONE demo,输出:Paul Sebula
。
这也仅占2个名字(仅第一个和最后一个)。注意如何访问姓氏,它是数组中的最后一个项目。
步骤:
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String fullName = distinguisedName.substring(3, distinguisedName.indexOf(','));
String[] nameParts = fullName.split(" ");
String firstName = nameParts[0];
String lastName = nameParts[nameParts.length-1];
这将对于其中的中间名/初始不存在,以及案件的工作。
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String[] commaSplit = distinguisedName.split(',');
String[] whitespaceSplit = commaSplit[0].split(' ');
String firstName = whitespaceSplit[0].substring(3);
String lastName = whiteSpaceSplit[2];
不要重新发明车轮。假设这些都能很好地形成的DN,看到在这个问题上对如何在不直接写自己的正则表达式解析接受的答案:Parsing the CN out of a certificate DN
一旦您已经提取CN
,那么你可以申请一些其他的分析技术建议(使用Java StringTokenizer
或String.split()
方法,正如其他人在这里所建议的,如果它已知只能被空格分开)。这假设您可以对CN
格式做出假设(例如,结果数组中的第一个元素是firstName
,最后一个元素是lastName
,其间的所有内容都是中间名/首字母)。
public static void main(String[] args) {
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String splitResult[]=distinguisedName.split(",")[0].split("=");
String resultTwo[]=splitResult[1].split("\\.");
String firstName=resultTwo[0].split(" ")[0].trim();
String lastName=resultTwo[1].trim();
System.out.println(firstName);
System.out.println(lastName);
}
输出
保罗
Sebula
很好的回答。如果语言具有可用的解析器,请使用该解析器。除非你有DN规范,否则让其他人处理这些丑陋的细节。 – tucuxi