例如,
字符串是:“{{aaa,bbb},{ccc,ddd},{eee,fff}}”
我希望程序自动将其拆分为字符串模式
模式为:{{...},{...},{...}}
什么是模式匹配正则表达式?
最佳答案
不确定你想要什么,所以这里是:
选项 1a
这将返回一个包含元素的String[]
:
[ "aaa,bbb",
"ccc,ddd",
"eee,fff" ]
如果您使用原始字符串调用它:
public static String[] split1(String source) {
final ArrayList<String> res = new ArrayList<String>();
if (source != null) {
source = source.trim();
if (source.startsWith("{") && source.endsWith("}")) {
final Pattern p = Pattern.compile("\\{([^}]+)\\}[,]?");
final Matcher m = p.matcher(source.substring(1).substring(0, source.length() - 2));
while (m.find()) {
res.add(m.group(1));
}
}
}
return (res.toArray(new String[res.size()]));
}
选项 1b
编辑:这比 1a 稍微简单,但结果相同:
public static String[] split3(final String source) {
final ArrayList<String> res = new ArrayList<String>();
if (source != null) {
final Pattern p = Pattern.compile("\\{(([^{}]+)[,]?)+\\}");
final Matcher m = p.matcher(source.trim());
while (m.find()) {
res.add(m.group(2));
}
}
return (res.toArray(new String[res.size()]));
}
选项 2a
这将返回一个包含元素的String[][]
:
[ [ "aaa", "bbb" ],
[ "ccc", "ddd" ],
[ "eee", "fff" ] ]
如果您使用原始字符串调用它:
public static String[][] split2(String source) {
final ArrayList<String[]> res = new ArrayList<String[]>();
if (source != null) {
source = source.trim();
if (source.startsWith("{") && source.endsWith("}")) {
final Pattern p = Pattern.compile("\\{([^}]+)\\}[,]?");
final Matcher m = p.matcher(source.substring(1).substring(0,
source.length() - 2));
while (m.find()) {
res.add(m.group(1).split(","));
}
}
}
return (res.toArray(new String[res.size()][]));
}
选项 2b
编辑:这比 2a 稍微简单,但结果相同:
public static String[][] split4(final String source) {
final ArrayList<String[]> res = new ArrayList<String[]>();
if (source != null) {
final Pattern p = Pattern.compile("\\{(((\\w+),(\\w+))[,]?)+\\}");
final Matcher m = p.matcher(source.trim());
while (m.find()) {
res.add(new String[] {
m.group(3),
m.group(4)
});
}
}
return (res.toArray(new String[res.size()][]));
}
<小时/>
下面是测试的主要方法:
public static void main(String[] args) {
final String TEST = "{{aaa,bbb},{ccc,ddd},{eee,fff}}";
System.out.println("split1 (Option 1a)");
for (final String str : split1(TEST)) {
System.out.println(str);
}
System.out.println("split2 (Option 2a)");
for (final String[] strs : split2(TEST)) {
System.out.println(Arrays.toString(strs));
}
System.out.println("split3 (Option 1b)");
for (final String str : split3(TEST)) {
System.out.println(str);
}
System.out.println("split4 (Option 2b)");
for (final String[] strs : split4(TEST)) {
System.out.println(Arrays.toString(strs));
}
}
关于java - 如何在字符串中搜索相同的模式,然后将它们放入Java中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3943659/