栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

仅将文件中的特定文本添加到数组列表,第2部分-Java

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

仅将文件中的特定文本添加到数组列表,第2部分-Java

最好使用正则表达式提取行上的数字,而不要尝试跟踪/猜测它(请参见下文)。

这是对代码的一种经过测试的重新创建,因为您引用了一些您未提供的类…但这有望对您有所帮助:

public static String getMatch(final String pattern, final String content) {    Pattern r = Pattern.compile(pattern);    Matcher m = r.matcher(content);    if (m.find()) {        return m.group(1);    } else {        return "";    }}public static void load(String fileName) throws FileNotFoundException {    List<String> places = new ArrayList<String>();    List<String> names = new ArrayList<String>();    List<String> nameDetails = new ArrayList<String>();    BufferedReader br = new BufferedReader(new FileReader(fileName));    String text;    String lastName = "";    try {        while ((text = br.readLine()) != null) { // extract num from start of line or empty if none.. String num = getMatch("^([0-9]+)\.", text); if (text.contains("Place:")) {     text = text.replaceAll("Place:", "");     places.add(text); } else if (text.contains(num + ". Name:")) {     text = text.replaceAll(num + ". Name:", "");     names.add(text);     lastName = text; } else if (text.contains(num + ". Name detail:")) {     text = text.replaceAll(num + ". Name detail:", "");     nameDetails.add(lastName + " had " + text); }        }    } catch (Exception e) {        System.err.println("Error: " + e.getMessage());    }    System.out.println("Places:" + places);    System.out.println("Names:" + names);    System.out.println("Name Details:" + nameDetails);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/440891.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号