繁体   English   中英

输入文本文件上的正则表达式浮点数

[英]Regular expression float number on a input text file

我需要做一份工资报告。 您必须键入具有文本信息的文件。 程序检查文件是否存在。 然后,制作程序的输出文件。 该程序在文本文件中打印工人的姓名,工作时间和比率。 我的程序只运行最后一组数字。

 import java.text.NumberFormat;
 import javax.swing.JTextArea;
 import java.awt.Font;
 import javax.swing.JOptionPane;
 import java.util.Scanner;
 import java.io.*;

 public class Homework {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {

    String answer, filename;


    filename = JOptionPane.showInputDialog("Enter the Input File Path:");

    File input = new File(filename);
    if (!input.exists()) {
        JOptionPane.showMessageDialog(null, "The input file:\n" + filename + "\ndoes not exist!");
        System.exit(0);
    }
    filename = JOptionPane.showInputDialog("Enter the Output File Path:");

    File output = new File(filename);
    if (output.exists()) {
        answer = JOptionPane.showInputDialog("The output file alaready exist!\nDo you want to overwrite it?");
        if (!answer.toLowerCase().equals("yes")) {
            System.exit(0);
        }
    }






    PrintWriter outFile = new PrintWriter(filename);
    Scanner in = new Scanner(input);

    double numberWords = 0, countNumber = 0;


   double value;

    String num, words, message;
    String amtStr, line = "";

    String alphaRegex = ".*[A-Za-z].*";
    String numRegex = ".*[0-9].*";



    while (in.hasNext()) {
        words = in.next();

        if (words.matches(alphaRegex)) {

            numberWords++;
            message = "The name is "+words+"\n"; //The Line is but leave +line+

     JOptionPane.showMessageDialog (null, message);



        } else if (words.matches(numRegex)) {
            countNumber++;
           num = in.next();


           message = "The number is "+num+"\n"; //The Line is but leave +line+

     JOptionPane.showMessageDialog (null, message);

             }



}
}

}

导致此问题的原因不是您的正则表达式。 它是while循环中的if语句。 当单词匹配numRegex时,然后将.next()签名为num,导致扫描程序跳过当前单词并选择下一个单词,在您的情况下,该单词也恰好是num。

以此替换while循环,它将起作用(我已经测试了代码):

while (in.hasNext()) {
    words = in.next();

    if (words.matches(alphaRegex)) {
        numberWords++;
        message = "The name is "+words+"\n";
        JOptionPane.showMessageDialog (null, message);

    } else if (words.matches(numRegex)) {
        countNumber++;
        num = words; // instead of num = in.next()
        message = "The number is "+num+"\n";
        JOptionPane.showMessageDialog (null, message);
    }
}

我假设您正在寻找一个正则表达式来标识文本中的浮点数。 如果是这样,这里是一个:

"(\\.\\d+)|(\\d+(\\.\\d+)?)"

这匹配任何后跟一个或多个数字的任何单独的十进制数,或匹配一个后跟一个或多个数字的可选十进制的任何数字序列。 请注意,如果这是一个问题,则不能解决前导零。

该网站是用于构建和测试正则表达式的绝佳资源:

http://www.regexr.com/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM