我如何解析字符串到一个数组 [英] How do I parse a String into an array
问题描述
我有一个字符串(下面的例子),我想解析到一个数组
I have a string (example below) that I would like to parse into an array
//只是个愚蠢的例子
字符串s =玛丽·马克{约翰·布朗}蜜獾棒棒糖{哦,我的上帝} {这种愚蠢};
我感兴趣的是打破这一字符串的String [] []或ArrayList中,所以,如果我叫:
I'm interested in breaking that string to String[][] or ArrayList, so if i called:
的String [] [] X =变换(S);
十大将包含这样的:
的String [] [] X = {{玛丽},{马克},{约翰,布朗},{亲爱的},{棒棒糖} {獾},{哦,我的,上帝},{这样的,愚蠢}};
我该怎么办呢?
编辑:改为二维数组
推荐答案
看来你可能会寻找类似
String s = "Mary Mark {John Brown} Honey lollipop Badger {Oh My God} {Such stupid}";
Pattern p = Pattern.compile("(?<=\\{)[^{}]+(?=\\})|\\w+");
Matcher m = p.matcher(s);
List<String[]> tokens = new ArrayList<String[]>();
while (m.find()) {
tokens.add(m.group().split("\\s+"));
}
String[][] result = tokens.toArray(new String[tokens.size()][]);
// lets see if it works as planned
System.out.println(Arrays.deepToString(result));
输出:
[[Mary], [Mark], [John, Brown], [Honey], [lollipop], [Badger], [Oh, My, God], [Such, stupid]]
说明:
(小于?= \\\\ {)[^ {}] +(?= \\\\})| \\\\ W +
是正规的前pression其中搜索
"(?<=\\{)[^{}]+(?=\\})|\\w+"
is regular expression which searches for
-
(小于?= \\\\ {)[^ {}] +(?= \\\\}这是不)
字符{
也不}
并与{
和}
(这些括号将不包括在内)。(小于?= ...)
和(?= ...)
是环视机制 - 或
\\\\ W +
一个或多个字母数字字符
(?<=\\{)[^{}]+(?=\\})
characters which are not{
nor}
and are between{
and}
(these brackets will not be included).(?<=...)
and(?=...)
are part of look-around mechanism- or
\\w+
one or more alphanumeric characters
之后,他们会发现所有这些记号,他们将在任何形式的分裂其中一个或多个空格 \\\\ S +
以创建一个字符串数组分开这么
After they will find all such tokens they will split them on any kind of one or more whitespace \\s+
to create separate array of strings so
-
foo的.split(\\\\ S +)
将成为数组[富]
-
富巴.split(\\\\ S +)
将成为数组[富,酒吧]
"foo".split("\\s+")
will become array["foo"]
"foo bar".split("\\s+")
will become array["foo", "bar"]
接下来,我使用的转换成数组列表变为二维列表的toArray
方法。
Next I convert list of such arrays into two dimensional list using toArray
method.
这篇关于我如何解析字符串到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!