简体   繁体   中英

Extracting specific substring from a java String in a generic way

I have a Java string of the following format == ocid1.instancepool.oc1.iad.aaaaaaaawqq4ibigdvw6esvmbia4zhs7dkaposzkzxuvir2ajtfyciih45fa

I want to extract the substring between the third and fourth dots, that is "iad". What is the best way to accomplish this? The logic should be generic and should work for any string which has four dots.

How about like this.

  • \\. escapes the . and is used as the target of split
  • split will return an array of the items between the .
  • referencing item 3 will get you the value you desire
String s = "ocid1.instancepool.oc1.iad.aaaaaaaawqq4ibigdvw6esvmbia4zhs7dkaposzkzxuvir2ajtfyciih45fa";
String result = s.split("\\.")[3];

System.out.println(result);

prints

iad

Check out Pattern and String for more information.

This is a rather basic 'how do I java' question: String manipulation comes up all the time, and most programming languages have a robust suite of options baked right into the language or standard libraries to do the job, fortunately!

You should look at Pattern - java's implementation of Regular Expressions which can do this quite well. Keep in mind that . is regexp-ese for 'any character', so to find an actual literal dot, you'd need to stick \\. in your regexp string literal instead - that's an actual . character.

If regexes don't strike your fancy, you can also simply combine a few invocations of indexOf to find the indices of the 3rd and 4th dot and then use substring to get iad out given those 2 indices. For more info on this, please review the String javadoc.

I don't think it's proper SO etiquitte to spoonfeed you the implementation here; at some point you're just asking SO to write your program one line at a time, nobody wins when that happens.

This seems like a duplicate of How can I use "." as the delimiter with String.split() in java .

The answer there is:

 String[] parts = myString.split("\\.");

The argument to split is a RegEx so you have to escape the "." which is reserved. See What special characters must be escaped in regular expressions? .

The array element with index 3 is the fourth entry:

 String thePartIWant = parts[3];

I'm not quite sure what you mean by "generic" but this is used a lot in Java. There are 3rd party libs to do this too - like Apache StringUtils.

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