简体   繁体   中英

How to split string with specific start and end delimiter?

public class Test {

public static void main(String[] args) {

    String str = "My CID is #encode2#123456789#encode2# I am from India";

    String[] tokens = str.split("#encode2#");

    for (int i = 0; i < tokens.length; i++) {
        // prints the tokens
        System.out.println(tokens[i]);
    }
}

}

Output will be My CID is 123456789 I am from India

But I want only 123456789 from this whole String and I want to use that 123456789 number for encryption.

I also use if(."#encode2#".equals(text)) condition but still not getting output.

How to write condition like need strat from #encode2# right part and end before #encode2#.

Use String's indexOf and lastIndexOf methods to find the index where the two #encode2# substrings start. Then, use substring to get the string between those two indices.

String str = "My CID is #encode2#123456789#encode2# I am from India";
String substring = "#encode2#";
int firstIdx = str.indexOf(substring);
int secondIdx = str.lastIndexOf(substring);
System.out.println(str.substring(firstIdx + substring.length(), secondIdx)); //123456789
    public String getToken() {

        String str = "My CID is #encode2#123456789#encode2# I am from India";

        int start = str.indexOf("#encode2#") + "#encode2#".length();
        int end = str.lastIndexOf("#encode2#");

        return str.substring(start, end);
    }

Note: This method only works if you have "#encode2#" twice in your String value. If you there are multiple instances of the Token you need, this doesn't work.

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