Ransford Okpoti's Blog

13 August, 2016

A Regular Expression (RegEx) To Match Integers and Doubles

Filed under: Java, JavaScript, Programming — ranskills @ 6:05 am

These regular expressions matches both the positive and negative variations of the data types specified below

  • integers – e.g., 1, 89, 81223, -7, etc.
  • floating point numbers (doubles or floats) – e.g., .0, 59.3, 300.12, -.87

 

The adopted approach was to avoid nested expressions which is not needed if it is only the number that is of interest and not its components like the decimal part and the fractional part.

JavaScript

var numberRegex = /(\-?\d*\.?\d+)/;

// Testing
var testNumber = "-45.8974";

console.log(numberRegex.test(testNumber));
console.dir(numberRegex.exec(testNumber));

Java

String numberRegex = "(\\-?\\d*\\.?\\d+)";

PHP

Coming soon.

 

USEFUL TOOLS

The site below allows the building and testing of regular expressions online, it is really nice with some colour coded tags and parenthesis colour matching to make a really complicated regular expression bearable to spot errors.

http://regexr.com/

 

Advertisements

Blog at WordPress.com.