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

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: