我有一个String
,其中包含一些单词。单词用花括号括起来。我想过滤掉所有单词并将其存储在数组中。 String
在下面。
String messages="Dear {GUEST_TITLE} {GUEST_FIRST_NAME} {GUEST_LAST_NAME}, Your reservation no {RESERVATION_NUMBER};
答案 0 :(得分: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()) {
String value = matcher.group(1);
System.out.println(value);
}
答案 1 :(得分:0)
您可以尝试以下操作:
首先用空""
替换所有花括号和逗号,然后用空格" "
分隔
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));
输出
[Dear, GUEST_TITLE, GUEST_FIRST_NAME, GUEST_LAST_NAME, Your, reservation, no, RESERVATION_NUMBER]
答案 2 :(得分:0)
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);
}
}
}
你在这里...
答案 3 :(得分:0)
您可以将RegEx与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());
}