简体   繁体   中英

Splitting string up by period

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?

employeeProfile.userProfile.shortname

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

Say we have this:

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

Then this works (module + 1's here and there):

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM