[英]Splitting string up by period
您好,我嘗試將以下字符串用於休眠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);
}
}
}
有人可以幫我獲得第三名嗎?
employeeProfile.userProfile.shortname
- employeeProfile.userProfile
- 用戶資料
- userProfile.shortName
說我們有這個:
int index1 = str.indexOf(".");
int index2 = str.lastIndexOf(".");
然后工作(模塊+1在這里和那里):
substring(0, index2);
substring(index1, index2);
substring(index1);
要獲得數字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
我認為使用Java的StringTokenizer可能會更好: http : //docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
您可以這樣設置:
String myString = "employeeProfile.userProfile.shortname";
String myDelimiter = ".";
StringTokenizer tokens = new StringTokenizer(myString,myDelimiter);
由此,您應該能夠得到所需的信息並使用令牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.