我有以下类型的字符串:
{{a}{b}{c}{d}{e}{f}{g}{h}}
其中 a 到 h 可以是任何字符串(不包含 {
和 {
)。
获取 a
, b
, c
,..h
的最有效方法是什么一个 Array
可能在 Java
中?
扫描每个字符对我来说似乎不是一个好的解决方案。
最佳答案
另一种选择是使用正则表达式,如下所示:
String text = "{{a}{b}{c}{d}{e}{f}{g}{h}}";
Pattern pattern = Pattern.compile("(?<=\\{)([^{}]*)(?=\\})");
Matcher matcher = pattern.matcher(text);
String[] result = new String[8];
for(int i = 0; i < result.length && matcher.find(); i++) {
result[i] = matcher.group(1);
}
System.out.println(Arrays.toString(result));
输出是:
[a, b, c, d, e, f, g, h]
请务必注意,至少在当前形式下,此解决方案最多只能找到 8 个字符串。如果您需要更动态的解决方案,请参阅 Jordi Castilla 的回答。
关于java - 从 Java 字符串中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32715739/