Harish Gupta
Harish Gupta

Reputation: 402

regex for numerics and decimals in java

Need a regex that allows the following valid values.(only decimals and numbers are allowed)

valid :

.1  
1.10  
1231313  
0.32131  
31313113.123123123 

Invalid :

dadadd.31232  
12313jn123  
dshiodah  

Upvotes: 4

Views: 4203

Answers (3)

Óscar López
Óscar López

Reputation: 236004

Try this:

String input = "0.32131";

Pattern pat = Pattern.compile("\\d*\\.?\\d+");
Matcher mat = pat.matcher(input);

if (mat.matches())
    System.out.println("Valid!");
else
    System.out.println("Invalid");

Upvotes: 2

Paul Vargas
Paul Vargas

Reputation: 42030

You can try the regular expression:

^(\d+|\d*\.\d+)$

Regular expression visualization

* Image generated using Debuggex: Online visual regex tester.

The explanation of this regular expression:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    \d+                      digits (0-9) (1 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    \d*                      digits (0-9) (0 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
    \.                       '.'
--------------------------------------------------------------------------------
    \d+                      digits (0-9) (1 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

* Explanation from Explain Regular Expressions.

Upvotes: 3

hwnd
hwnd

Reputation: 70732

If you want to be strict on your allowed matches:

^[0-9]*\.?[0-9]+$

Explanation:

^         # the beginning of the string
 [0-9]*   #  any character of: '0' to '9' (0 or more times)
 \.?      #  '.' (optional)
 [0-9]+   #  any character of: '0' to '9' (1 or more times)
$         # before an optional \n, and the end of the string

Live Demo

Upvotes: 6

Related Questions