有 Java 编程相关的问题?

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

java我想检查输入字符串的格式是否正确

我想检查输入字符串并验证它是否是正确的数字格式,以及是否编写了以下正则表达式[+-]?[0-9]*[.]?[0-9]*[e]?[+-]?[0-9]+.但不幸的是,对于--6或++6,它的输出为true

import java.util.*;

public class Main {
    public static void main(String args[]) throws Exception {
        //Scanner
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        in.nextLine();
        while(--t >= 0) {
            String string = in.nextLine();
            string = string.trim();
            //System.out.println(string);
            String regex = "[+-]?[0-9]*[.]?[0-9]*[e]?[+-]?[0-9]+";
            //System.out.println(string.matches(regex));
            if(string.matches(regex)) {
                System.out.println(1);
            }
            else {
                System.out.println(0);
            }
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    这是由于正则表达式字符串中的第二个[+-]?而匹配的。在++6 or 6中,它首先匹配存在的第一个+-,然后再次匹配存在的第二个+-,然后匹配数字

    但你很接近。如果存在指数,则只需匹配第二个[+-]?。因此,只需将整个指数部分放在括号内,并在末尾添加一个?即可。这样,只有在第二个+-前面有一个e/E时,才能匹配它

    ^[+-]?([0-9]+)?[.]?[0-9]*([eE][+-]?[0-9]+)?$
    

    enter image description here

    Regex Demo

  2. # 2 楼答案

    我会用这个

    ^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$

    格式化

     ^ 
     [+-]? 
     (?:
          \d+ 
          (?: \. \d* )?
       |  
          \. \d+ 
     )
     (?: [eE] [+-]? \d+ )?
     $