我需要获得字符串中用符号« »
框起来的单词:
示例:
String phrase = "«User» of the «application»";
String words[] = phrase.indexOf("«") + phrase.indexOf("»")
words[0] = "User";
words[1] = "application";
问题是,这个解决方案只获得了第一个词:"用户",我需要所有的词都框起来。。。
我该怎么做?
按如下操作:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
String phrase = "«User» of the «application»";
Pattern p = Pattern.compile("«\w+»");
Matcher m = p.matcher(phrase);
while (m.find()) {
list.add(m.group().replaceAll("«", "").replaceAll("»", ""));
}
String words[] = list.toArray(new String[0]);
System.out.println(Arrays.toString(words));
}
}
输出:
[User, application]
String phrase = "«User» of the «application»";
Pattern p = Pattern.compile("«\w+»");
Matcher m = p.matcher(phrase);
while (m.find()) {
String text = m.group().substring(1,m.group().length()-1);
System.out.println(text);
}