1

这是我的第一个问题,很抱歉我的英语不好

我只想从字符串中提取具有字母和数字组合的单词并将其存储在数组中

我尝试这段代码,但我没有得到我想要的

String temp = "74 4F 4C 4F 49 65  brown fox jump over the fence";
String [] word = temp.split("\\W");

这是我想要的结果(只有单词,没有空数组)

brown
fox
jump
over
the
fence

请帮忙,谢谢!

4

2 回答 2

2

您可以使用:

String temp = "74 4F 4C 4F 49 65  brown fox jump over the fence";
List<String> arr = new ArrayList<String>();
Pattern p = Pattern.compile("(?i)(?:^|\\s+)([a-z]+)");
Matcher m = p.matcher(temp);
while (m.find())
    arr.add(m.group(1));

// convert to String[]
String[] word = arr.toArray(new String[0]);
System.out.println( Arrays.toString(word) );

输出:

[brown, fox, jump, over, the, fence]
于 2013-11-02T11:01:55.557 回答
2

根据@anubhava 的回答,您可以执行类似的操作

String temp = "74 4F 4C 4F 49 65  brown fox jump over the fence";
Pattern pattern = Pattern.compile("\\b[A-Za-z]+\\b");
Matcher matcher = pattern.matcher(temp);

while (matcher.find()) {
  System.out.println("Matched " + matcher.group());
}
于 2013-11-02T11:13:22.843 回答