如何将句子中所有类似的单词转换为数组

时间:2014-07-11 11:40:18

标签: java

我有一个字符串

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]

怎么做?

3 个答案:

答案 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());
}