我如何解析字符串到一个数组 [英] How do I parse a String into an array

查看:229
本文介绍了我如何解析字符串到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串(下面的例子),我想解析到一个数组

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆