【问题标题】:How to remove elements from a line in a text file once it is in an array?一旦文本文件在数组中,如何从文本文件的行中删除元素?
【发布时间】:2016-05-03 00:44:05
【问题描述】:

所以,我有一个看起来完全一样的文本文件:

<sgkljsd>::=<sdfasfda> <sadfasf>
<lol>::=<dgs> <pdja> <l>|<np>
<or>::hello|howdy
<sdfas>::=<saf>|<sdf> <adlp>
<needd>::=huge|massive|big|tall

所以,在这个文本文件中,不需要第 1 行和第 2 行,所以我跳过它们。但是,我需要第 3 行和第 5 行中的单词。我当前的代码在“|”处拆分第三行所以我要么得到“你好”,要么得到“::hello”。那么有没有办法删除一行中的元素?在第 3 行和第 5 行中,我只需要在“|”处拆分单词。我想摆脱“”中的项目。

我当前的代码如下:

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a file name: ");
        String fileName = scan.nextLine();
        File infile = new File(fileName);
        Scanner readIt = new Scanner(infile);

        // removes first line of file
        String junkLine1 = readIt.nextLine();

        // removes second line of file
        String junkLine2 = readIt.nextLine();

        //gets random <word> from text file
        String word = readIt.nextLine();
        // breaks it into "<or>hello" and "howdy"
        String[]word1 = word.split("\\|");
        int rnd = r.nextInt(word1.length);
        String rnd_word = (word1[rndDp]);
        System.out.println(rnd_word);

所以,我想做的是随机选择数组中的单词并随机打印出问候语,但我似乎无法弄清楚如何删除不必要的文本。感谢您提供有关如何解决或解决此问题的任何想法。

【问题讨论】:

  • String word = readIt.nextLine(); word = word.substring(word.indexOf("::")+2); 这将修剪 word 以在 :: 之后开始。
  • @BethanyLouise 谢谢,这部分工作。但是,第一个单词被等号抓住了。有没有办法把它也去掉?
  • 你可以使用if (word.contains("=")) { word = word.substring(word.indexOf("=")+1); }
  • 你为什么用这个编辑毁了这个问题
  • @bmarkham 不确定发生了什么。感谢您修复。我正在重新输入所有内容

标签: java arrays split


【解决方案1】:

您可以摆脱 用正则表达式替换它们:

"<needd>::=huge|massive|big|tall".replaceAll("<.+?>", "");

返回:

::=huge|massive|big|tall

"<needd>::=huge|massive|big|tall".replaceAll("<.+?>::=", "");

返回:

huge|massive|big|tall

或者你也可以拆分:

"<needd>::=huge|massive|big|tall".split("<.+?>|:+|\\||=");

这将返回一个字符串数组,其中包含:

{huge, massive, big, tall}

您可以在此处尝试以上组合:http://www.regexpal.com/

【讨论】:

  • 有没有办法让它变得巨大|巨大|大|高?就像没有 ::=
  • replaceAll("<.>::=", "");
  • 谢谢!完美地工作,正是我需要的
  • 嘿@PeteytheProgrammer,我的回答解决了你的问题,你能接受它作为问题的答案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-01
  • 2013-05-13
  • 2022-01-27
  • 2010-10-14
  • 2023-02-08
  • 2015-12-22
相关资源
最近更新 更多