2013-01-23 72 views
0

我正在使用Spring Security 3.1 Active Directory。檢索第一個OU以搜索distinguishedName屬性

我有一個AD結構,我需要從AD結構distinguishedname屬性中獲取OU值。

我想要的OU將始終是最後一個DC之後的第一個OU。

下面

是我的代碼示例 - 我需要得到myCompany的OU值,必須有一個更好的方式來做到這一點:

公共類的測試{

public static void main(String[] args) { 

    String s = "cn=harry,cn=group,ou=myCompany,ou=customers,dc=this,dc=that"; 

    System.out.println("s: "+s); 

    String s1 = s.substring(s.indexOf("ou=") + 3); 

    System.out.println("s1: "+s1); 

    String s2 = s1.substring(s1.indexOf(""), s1.indexOf(",ou=")); 

    System.out.println("s2: "+s2); 

} 

}

這輸出以下內容:

s: cn=harry,ou=myCompany,ou=customers,dc=this,dc=that 
s1: myCompany,ou=customers,dc=this,dc=that 
s2: myCompany 

任何人都可以幫忙嗎?

回答

1

正則表達式!選擇下面的風味(第一或第二):

public static void main (String[] args){ 
    String s = "cn=harry,cn=group,ou=users,ou=myCompany,ou=customers,dc=this,dc=that"; 

    String first = s.replaceAll(".*?,ou=(.*?),.*", "$1"); 
    String middle = s.replaceAll(".*?,ou=.*?,ou=(.*?),.*", "$1"); 
    String third = s.replaceAll(".*,ou=(.*?),.*", "$1"); 

    System.out.println(first); 
    System.out.println(middle); 
    System.out.println(third); 
} 
+0

對不起,我犯了一個錯誤。我需要這個永遠是第二個OU,而不是第一個? – babb

+0

謝謝。我真的很感激快速的迴應。因爲它去了,我已經調查該字符串是acutally:String s =「cn =哈里,ou =用戶,ou =我的公司,ou =客戶,dc =這,dc = that」,我需要能夠得到中間ou這是我的公司。你能幫忙嗎? – babb

+0

更新了答案。如果您認爲這有幫助,不要忘記關閉問題並投票。乾杯 – Andre