有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

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

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

编写这段代码将(而且可能会)是一个有趣的练习,但必须有一个现有的库已经提供了这一功能

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


共 (2) 个答案

  1. # 1 楼答案

    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. # 2 楼答案

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

    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