Reputation: 7788
Hello I have the following string I'm trying to split up for the hibernate createAlias and query restrictions.
I need to split the string in to three parts.
employeeProfile.userProfile.shortname
1. employeeProfile.userProfile
2. userProfile
3. userProfile.shortName
I'd also like it to be dynamic to do a different length string.
employeeProfile.userProfile.anotherClass.shortname
1. employeeProfile.userProfile.anotherClass
2. userProfile.anotherClass
3. anotherClass.shortName
I was able to get most of it to work with the exception of number three using the following code.
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);
}
}
}
Could someone help me to get number 3?
Upvotes: 0
Views: 100
Reputation: 5869
To get number 3 you can use a regular expression. A regular expression that takes the last two item will be:
[a-zA-z]+\.[a-zA-z]+$
Get number 3 by using the following code:
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));
}
This will print:
anotherClass.shortname
Upvotes: 1
Reputation: 6969
employeeProfile.userProfile.shortname
- employeeProfile.userProfile
- userProfile
- userProfile.shortName
Say we have this:
int index1 = str.indexOf(".");
int index2 = str.lastIndexOf(".");
Then this works (module + 1's here and there):
substring(0, index2);
substring(index1, index2);
substring(index1);
Upvotes: 1
Reputation: 4453
Take a look at String.split(). For example, you could do something like the following:
String[] tmp="foo.bar".split(".");
Once you have it in this form you can do whatever you need to with it.
Upvotes: 1
Reputation: 687
I think you might have better luck with Java's StringTokenizer: http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
You could set it up like this:
String myString = "employeeProfile.userProfile.shortname";
String myDelimiter = ".";
StringTokenizer tokens = new StringTokenizer(myString,myDelimiter);
From this, you should be able to get what you need and play with the tokens.
Upvotes: 1