从字符串中提取两种类型的文本

时间:2018-11-07 11:00:09

标签: java

我有一个字符串,其中包含两种(通常为N)类型的数据,以打开和关闭标记分隔:

type1a <: type2a :> type1b <: type2b :> type1-c

这种混合数据有许多现实生活中的例子,例如代码和注释(可能还有javadoc注释),纯html和脚本部分等。

我想将字符串拆分为包含不同类型数据的字符串;仅("type1a", "type2a", "type1b", "type2b", "type1-c")的数组/列表是不够的,因为我需要数据类型。

对此进行编码(可能会)是一个有趣的练习,但是必须有一个已经提供此功能的现有库。

是否有一个Java库提供这样的功能,即将一个字符串分成多个不同性质的片段,并保留每个片段类型的信息?

2 个答案:

答案 0 :(得分:0)

public static List<String> read(String str) {
    List<String> res = new ArrayList<>();

    try (Scanner scan = new Scanner(str)) {
        scan.useDelimiter("\\s*<:\\s*|\\s*:>\\s*");

        while (scan.hasNext())
            res.add(scan.next());
    }

    return res;
}

答案 1 :(得分:0)

在我看来,您想提取对列表:

public static void main(String[] args) {
    String opening = "<:";
    String closing = ":>";
    String str = " type1a  <:  type2a :> type1b <:  type2b :> type1c   <: type2c :>  ";

    String[] splitted = str.split(closing);
    List<Pair<String, String>> list = new ArrayList<>();

    for (String item : splitted) {
        if (item.trim().isEmpty())
            break;

        int index = item.indexOf(opening);
        String first = item.substring(0, index).trim();
        String second = item.substring(index + opening.length()).trim();
        Pair<String, String> p = new Pair<>(first, second);
        list.add(p);
    }

    for (Pair<String, String> p : list) {
        System.out.println(p.getKey() + " " + p.getValue());
    }
}

将打印

type1a type2a
type1b type2b
type1c type2c
相关问题