代码之家  ›  专栏  ›  技术社区  ›  18446744073709551615

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

  •  -3
  • 18446744073709551615  · 技术社区  · 7 年前

    我有一个字符串,它包含两种类型的数据(在一般情况下是N),由打开和关闭标记分隔:

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

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

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

    编写这段代码可能会是一个有趣的练习,但必须有一个已经提供此功能的现有库。

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

    2 回复  |  直到 7 年前
        1
  •  0
  •   Oleg Cherednik    7 年前
    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;
    }
    
        2
  •  0
  •   forpas    7 年前

    在我看来你想提取一个配对列表:

    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