简体   繁体   English

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

[英]I want to check the input string if it is a correct format

I want to check the input string and validate if it is a correct number format and have written the following regex. 我想检查输入字符串并验证它是否是正确的数字格式,并编写了以下正则表达式。 [+-]?[0-9]*[.]?[0-9]*[e]?[+-]?[0-9]+. but unfortunately it is outputting true for --6 or ++6 但不幸的是,它对于--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);
            }
        }
    }
}

This is matching due to the second [+-]? 这是由于第二个[+-]?相匹配[+-]? in your regex string. 在您的正则表达式字符串中。 In ++6 or --6 , it first matches the first +- since it is present, then again match the second +- since it was present, and then the digit. ++6 or --6 ,它首先匹配第一个+-因为它已经存在,然后再次匹配第二个+-因为它已经存在,然后是数字。

But you were close. 但是你很亲近。 What you want to do is only match the second [+-]? 您只想匹配第二个[+-]? if there is an exponent present. 如果有指数存在。 So just make the whole exponent part optional by enclosing in brackets and adding a ? 因此,只需将整个指数部分包括在方括号中并添加一个?使其成为可选部分即可? at the end. 在末尾。 Like this, you will match the second +- only if there is an e/E in front of it. 这样,仅当前面有e/E时,您才匹配第二个+-

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

在此处输入图片说明

Regex Demo . 正则表达式演示

I would use this 我会用这个

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

Formatted 格式化的

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

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

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