Regular expression to judge numbers

Judge positive and negative integers, positive and negative decimals

Expression: ^[+-]?([0]{1,1}|[1-9]{1,1}[0-9]*?)[.]?[\\d]{1,} $

import java.util.Scanner;

import java.util.regex.Pattern;

public static void main(String[] args) {

Pattern pattern = Pattern.compile("^[+-]?([0]{1,1}|[1-9]{1,1}[0-9]*?)[.]?[\\d]{1,}$");

Scanner sc = new Scanner(System.in);

while (sc.hasNext()) {

String sss = sc.nextLine();

System.out.println(pattern.matcher(sss).matches());

}

}

test case

-0.1        true
+0.1        true
0.1        true
1.0        true
-1.0        true
+1.0        true
0.01        true
-0.01        true
+0.01        true
01.1        false
10.1        true
10.01        true
10.        false
.01        false
-345        true
+456        true

345.345345        true
5.555346345        true
34534534535345345345353635353536353467345345345.345345346345346345685679564358560898345234645674569680545        true

567..778        false

Expression^[+-]?([0]{1,1}|[1-9]{1,1}[0-9]*?)[.]?[\\d]{1,}$ explain

^ and $ delimiters

() is used when or

| or

* means n more than 0 matches or multiple matches

? Indicate whether the condition in front of the mark is optional

Question mark (?) and asterisk (*): Following a pattern content is a quantifier, which is used to limit the number of times the pattern content matches.

\\d represents a number from 0 to 9

{1,} means at least one match. Add braces after the pattern to match the number of times to indicate the quantifier. The form is{lower limit, upper limit}

 

Guess you like

Origin blog.csdn.net/u010952056/article/details/109787298