2013-10-30 38 views
0

你好,我有以下字符串我想分解爲休眠createAlias和查詢限制。按時間段分割字符串

我需要將字符串分成三部分。

employeeProfile.userProfile.shortname

1. employeeProfile.userProfile 
2. userProfile 
3. userProfile.shortName 

我也喜歡它是動態做了不同長度的字符串。

employeeProfile.userProfile.anotherClass.shortname

1. employeeProfile.userProfile.anotherClass 
2. userProfile.anotherClass 
3. anotherClass.shortName 

我能得到大部分有三個一批使用下面的代碼異常的工作。

public void hasAlias(Criteria t, final Map<String, Object> map) { 
    for (Map.Entry<String, Object> entry : map.entrySet()) { 
     String key = entry.getKey(); 
     if (key != null && key.contains(".")) { 
      key = key.substring(0, key.lastIndexOf(".")); 
      String value = key.contains(".") ? key.substring(key.lastIndexOf(".") + 1, key.length()) : key; 
      t.createAlias(key, value); 
     } 
    } 
} 

有人可以幫我拿到3號嗎?

回答

1

String.split()看看。例如,你可以做類似如下:

String[] tmp="foo.bar".split("."); 

一旦你在這個表格你可以把它任何你需要它。

1

employeeProfile.userProfile.shortname

  1. employeeProfile.userProfile
  2. USERPROFILE
  3. userProfile.shortName

說我們有這樣的:

int index1 = str.indexOf("."); 
int index2 = str.lastIndexOf("."); 

那麼這(在這裏和那裏模塊+ 1級的)工作原理:

  1. substring(0, index2);
  2. substring(index1, index2);
  3. substring(index1);
+0

你在哪裏獲得3號指數? –

+0

應該是'index1'。糾正。 – iluxa

+0

@George這不適用於第二個例子。 3號將是不正確的。 – summerbulb

1

要獲得數字3,您可以使用正則表達式。正則表達式,是以最後兩個項目將是:

[a-zA-z]+\.[a-zA-z]+$ 

獲取數3通過使用下面的代碼:

Pattern pattern = Pattern.compile("[a-zA-z]+\\.[a-zA-z]+$"); 
Matcher matcher = p.matcher("employeeProfile.userProfile.anotherClass.shortname"); 

if (m.find()) { 
    System.out.println(m.group(1)); 
} 

這將打印:

anotherClass.shortname 
1

我想你可能與Java的StringTokenizer有更好的運氣:http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html

你可以設置它u p是這樣的:

String myString = "employeeProfile.userProfile.shortname"; 
String myDelimiter = "."; 
StringTokenizer tokens = new StringTokenizer(myString,myDelimiter); 

從這個,你應該能夠得到你需要和玩的令牌。