示例我有一个字符串
"123<a>3213<b>3434343<c>,example <d><1><2><3>"
我想通过符号"<>"
如何获取列表 [a,b,c,d,1,2,3] ???
答案 0 :(得分:5)
您可以使用StringUtils.substringsBetween(String str, String open, String close)。
String[] parts = StringUtils.substringsBetween("123<a>3213<b>3434343<c>,example <d><1><2><3>", "<", ">");
答案 1 :(得分:5)
您想要<..>
之间的文字。在给定String
之间使用Pattern
和Matcher
,同时在<..>
String text = "123<a>3213<b>3434343<c>,example <d><1><2><3>";
Pattern pattern = Pattern.compile("<(.*?)>"); // reluctant quantifier
Matcher matcher = pattern.matcher(text);
List<String> entries = new LinkedList<>();
while (matcher.find())
entries.add(matcher.group(1)); // group 0 is the whole match, we only want what's between <>
System.out.println(entries);
打印
[a, b, c, d, 1, 2, 3]
答案 2 :(得分:2)
未经测试,几乎没有防弹,小错误检查,但它应该工作。当然事情可能会更好,这只是来自记忆。
public List<String> getThings(String source) {
char[] chars = source.toCharArray();
boolean capturing = false;
List<String> result = new ArrayList<String>();
String token = "";
for(char c : chars) {
if (!capturing) {
if (c == '<') { // found open delimiter, start capture.
capturing = true;
continue;
}
} else {
if (c == '>') { // Found closing delimiter, stop capture.
results.add(token);
token = "";
capturing = false;
continue;
}
token = token + c;
}
}
if (!scanning) {
throw new RuntimeException("Source string ended with missing closing '>'");
}
return results;
}