我有一个字符串
String sentence = "I tried to speak @ty Spanish @ty-1, and my@ty-2 friend tried to@ty-3 speak English @ty.";
我希望@ty,@ ty-1等所有单词都成为一个ArrayList。 @ty词是动态的,在不同的场景中不断变化,如上所示。
结果应该是这样的: - arrayList应该包含元素
上述句子[@ty, @ty-1, @ty-2, @ty-3, @ty]
。
怎么做?
答案 0 :(得分:1)
您可以使用reges:
public static void main(String[] args) {
String sentence = "I tried to speak @ty Spanish @ty-1, and my@ty-2 friend tried to@ty-3 speak English @ty.";
Pattern p = Pattern.compile("(@ty.*?)(?=[,\\s+\\.])");
Matcher m = p.matcher(sentence);
while (m.find()) {
System.out.println(m.group());
}
}
O / P:
@ty
@ty-1
@ty-2
@ty-3
答案 1 :(得分:0)
为什么regex
?你可以试试这样的东西
String sentence = "I tried to speak @ty Spanish @ty-1, and my@ty-2 friend tried to@ty-3 speak English @ty.";
String[] arr=sentence.replaceAll(",","").split(" ");
List<String> list=new ArrayList<>();
for(String i:arr){
if(i.contains("@")){
list.add(i.substring(i.indexOf("@"),i.length()));
}
}
System.out.println(list);
输出:
[@ty, @ty-1, @ty-2, @ty-3, @ty]
答案 2 :(得分:0)
试试这些
Pattern pattern=Pattern.compile("@ty[-\\W][0-9]*");
Matcher matcher=pattern.matcher(sentence);
while(matcher.find())
{
System.out.println(matcher.group());
}