简体   繁体   中英

how can I get particular string(sub string ) from a string

I have string like

{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}
{Imapact}{assest}{custom_23_multiplication}.

From this I want only those sub string which contains "custom".

For example from above string I want only

{Custom_21_addtion}{custom_22_substration}{custom_23_multiplication}.

How can I get this?

You can use a regular expression, looking from {custom to } . It will look like this:

Pattern pattern = Pattern.compile("\\{custom.*?\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputString);

while (matcher.find()) {
    System.out.print(matcher.group());
}

The .* after custom means 0 or more characters after the word "custom", and the question mark limits the regex to as few character as possible, meaning that it will break on the next } that it can find.

If you want an alternative solution without regex:

String a = "{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}{custom_23_multiplication}";
        String[] b = a.split("}");
        StringBuilder result = new StringBuilder();
        for(String c : b) {
            // if you want case sensitivity, drop the toLowerCase()
            if(c.toLowerCase().contains("custom"))
                result.append(c).append("}");
        }
        System.out.println(result.toString());

you can do it sth like this:

StringTokenizer st = new StringTokenizer(yourString, "{");
List<String> llista = new ArrayList<String>():

Pattern pattern = Pattern.compile("(\W|^)custom(\W|$)", Pattern.CASE_INSENSITIVE);

while(st.hasMoreTokens()) {

String string  = st.nextElement();
Matcher matcher = pattern.matcher(string);
if(matcher.find()){
llista.add(string);
}

}

Another solution:

String inputString = "{Action}{RequestId}{Custom}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}" ;
String strTokens[] =  inputString.split("\\}");

for(String str: strTokens){
    Pattern pattern = Pattern.compile( "custom", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputString);
    if (matcher.find()) {
        System.out.println("Tag Name:" + str.replace("{",""));
    }  
}

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