简体   繁体   中英

Selecting special words from string

I have a String that contains some words. Words are enclosed by curly braces. I want to filter out all words and store it in an Array . String is below.

String messages="Dear {GUEST_TITLE} {GUEST_FIRST_NAME} {GUEST_LAST_NAME}, Your reservation no {RESERVATION_NUMBER};

Do it with regex ;

Pattern CURLY_DELIMITER_REGEX = Pattern.compile("\\{(\\w+)\\}");
String messages = "Dear {GUEST_TITLE} {GUEST_FIRST_NAME} {GUEST_LAST_NAME}, Your reservation no {RESERVATION_NUMBER}";
Matcher matcher = CURLY_DELIMITER_REGEX.matcher(messages);
while (matcher.find()) {
    String value = matcher.group(1);
    System.out.println(value);
}

you can try this:

First replace all curly braces and comma with empty "" and then split it with space " "

String messages="Dear {GUEST_TITLE} {GUEST_FIRST_NAME} {GUEST_LAST_NAME}, Your reservation no {RESERVATION_NUMBER}";
char[] charr  = messages.replaceAll("[}{,]","").split(" "); 
System.out.println(Arrays.toString(charr)); 

output

[Dear, GUEST_TITLE, GUEST_FIRST_NAME, GUEST_LAST_NAME, Your, reservation, no, RESERVATION_NUMBER]
import java.util.*;

public class Main
{
    public static void main(String[] args) {
        String messages="Dear {GUEST_TITLE} {GUEST_FIRST_NAME} {GUEST_LAST_NAME}, Your reservation no {RESERVATION_NUMBER}";
        int len = messages.length();
        List<String> list = new ArrayList<>();
        for(int i=0; i< len; i++){
            if(messages.charAt(i) == '{'){
                int indexOfClosingBracket = messages.indexOf('}', i+1);
                list.add(messages.substring(i+1, indexOfClosingBracket));
                i = indexOfClosingBracket;
            }
        }

        for(String s : list){
            System.out.println(s);
        }
    }
}

Here you go...

You can use RegEx with ArrayList:

List<String> result_array = new ArrayList<String>();
    int i = 0;
    Pattern CURLY_DELIMITER_REGEX = Pattern.compile("\\{(\\w+)\\}");
    String messages = "Dear {GUEST_TITLE} {GUEST_FIRST_NAME} {GUEST_LAST_NAME}, Your reservation no {RESERVATION_NUMBER}";
    Matcher matcher = CURLY_DELIMITER_REGEX.matcher(messages);
    while (matcher.find()) {
        result_array.add(matcher.group(1));
        i = i + 1;
    }
    System.out.print("Now the Result Array is :\n");
    for (String item : result_array) {
        System.out.println(item.toString());
    }

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