如何将一个句子中所有相似的单词排列成一个数组



我有一个字符串

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..等放到一个数组列表中@ty词是动态的,在不同的场景中不断变化,如上所示。

结果应该是:-arrayList应该包含元素[@ty, @ty-1, @ty-2, @ty-3, @ty]

如何做到这一点?

您可以使用正则表达式:

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

为什么选择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]

试试这些

Pattern pattern=Pattern.compile("@ty[-\W][0-9]*");
Matcher matcher=pattern.matcher(sentence);
while(matcher.find())
{
    System.out.println(matcher.group());
}

最新更新