【问题标题】:Java - How to read ints or doubles/floats of a fileJava - 如何读取文件的整数或双精度/浮点数
【发布时间】:2016-04-02 03:59:18
【问题描述】:

到目前为止,我有这段代码,但我在使用分隔符时遇到了问题(我是正则表达式和文件读取的新手)。

File file = new File(ROOT_FOLDER + fname);

    Scanner scanner = null;
    try {
        Pattern p = Pattern.compile("(?=\\D+)(?=[^\\.])");
        scanner = new Scanner(file).useDelimiter(p);

        while (scanner.hasNext()) {
            String next = scanner.next();
            UI.println(next);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new Error(e);
    } finally {
        if (scanner != null)
            scanner.close();
    }

文件示例

Samples from database of fake names from http://www.fakenamegenerator.com/
All details are fictious!!

Mr. Jake M Goodwin 11 Yarmouth Road Mahora 4120 JakeGoodwin@teleworm.us (022) 6735-347 1998 Rolls-Royce Silver Spur 100.9 184
Mr. Samuel D Law 140 Small Street Dunedin Central 9016 SamuelLaw@cuvox.de (028) 0699-710 2001 Dodge Durango 113 180

让我感到困惑的是,如果我使用默认的空格分隔符,那么像 (028) 这样的数字将不会被检测为带有 hasNextDouble() 的数字(但我认为使用正则表达式意味着我可以只使用 hasNext()无论如何)。

我需要使用什么合适的分隔符?我正在考虑类似的事情:任意数量的非数字连续,只要它不是一个点。

【问题讨论】:

  • 你能给你的程序提供一个示例输入和输出吗?
  • 。在一堆空格中偶尔出现的数字或单点,或点后跟数字。

标签: java regex java.util.scanner


【解决方案1】:

你可以用这个:

try
    {
        //regex for matching only numbers and dot
        Pattern p = Pattern.compile("[^0-9.]");
        scanner = new Scanner(new FileReader(FILE_PATH)).useDelimiter(p);
        while (scanner.hasNext()) {
            String next = scanner.next();
            if(!next.equals("") && !next.equals(".")) {
                System.out.println(next);
            }
        }
    }
    catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (scanner != null)
            scanner.close();
    }

输入:

来自http://www.fakenamegenerator.com/的假名数据库的样本 所有细节都是虚构的!先生。 Jake M Goodwin 11 Yarmouth Road Mahora 4120 JakeGoodwin@teleworm.us (022) 6735-347 1998 劳斯莱斯 Silver Spur 100.9 184 Samuel D Law 先生 140 Small Street Dunedin Central 9016 SamuelLaw@cuvox.de (028) 0699-710 2001 Dodge Durango 113 180

输出:

11 4120 022 6735 347 1998 100.9 184 140 9016 028 0699 710 2001年 113 180

【讨论】:

  • 哇,这比使用正则表达式简单多了。我觉得我以前曾考虑过这一点,但在我的脑海中拒绝了它,转而支持更复杂的正则表达式解决方案。谢谢!
  • 为什么你的正则表达式中没有\` before the .`?我认为. 表示任何字符。而且,0-9. 是指 0-9 数字,然后是 . 还是表示 0-9.
  • 括号表达式 [] 匹配括号中包含的单个字符。例如,[abc] 匹配“a”、“b”或“c”。 ^0-9。表示否定集合 - 匹配任何不在集合中的字符。
  • 我明白了。那么 ^ 是否意味着除了 0-9 之外的所有内容,或者除了 0-9 或一个点之外的所有内容
  • 表示除 0-9 或点之外的所有内容。一个非常好的可以练习的地方是RegExr
猜你喜欢
  • 2011-05-09
  • 2011-07-12
  • 1970-01-01
  • 2022-01-25
  • 2015-02-08
  • 2022-11-19
  • 1970-01-01
  • 2014-04-25
相关资源
最近更新 更多