Pattern matching for actual numbers using regex

I have a question out of my own curiosity. Although I have a working solution, I am interested to know why one method is successful while the other isn't.

I was in need of a regular expression for validating if a user input is a valid number. Here are some examples:

87

887.65

-87

-87.65

My initial attempt was like this:

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

It worked well, but it accepted strings like '7x', '1a', '89p' which were not desired. My updated solution is as follows and seems to be working correctly:

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

The second one (with the '+') is more concise, yet I'm unsure why the first one allowed letters and the second did not. Can anyone see what I might be overlooking?

Answer №1

When using regex, be sure to escape certain characters like "." in order to match them literally. Otherwise, the regex will match any character instead. Additionally, the "+" operator requires at least one occurrence of a decimal, ensuring that it won't match patterns like "7x", but will match patterns like "7x1". Check out this Regex demo for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhance your Material-UI ListItems with dynamic ripple colors when using React-Router NavLink

Currently, I am attempting to nest a Material-UI <ListItem button> within a react-router <NavLink>. While functionality is present, I have observed that the ripple colors on the <ListItem button> are being altered by the <NavLink> C ...

Utilize emit to distribute / allocate a variable

I have some variables stored in a file called server.js (and they tend to change frequently). My goal is to pass these variables to client.js whenever the client sends a request (triggers the 'validate' event). Even though the event is triggered, ...

Tips for embedding JavaScript code into HTML attributes when using React JS

return( <div> <Loading loadingMessage="Running "{this.state.programName}" program"/> </div> ); It appears that the value of the loadingMessage attribute is syntactically incorrect, but I have a specific requirement. I need to ret ...

Failed to transfer CryptoKey to Express server

When I generate a CryptoKeyPair object on the client using the WebCrypto API, and try to send it to my express server using the fetch API, the req.body on the server side ends up being an empty object. What could be causing this issue? This is how I am ge ...

How can I implement a progress bar for file uploads in AngularJS when a button is

Currently, I am experimenting with image upload functionality that includes an image preview feature. My goal is to display a progress bar when the user clicks the upload button and show the upload status on the progress bar using Angular. Can anyone provi ...

Unexpected Token E encountered in the Twitter stream.on function

I'm currently in the process of setting up a search button on my web application that will pull all Twitter tweets related to the search input using the streaming API. Below is my client-side code: <form class="navbar-form navbar-left" role="sear ...

When a div tag containing PHP is empty, it should either be hidden or show specific text based on your requirements

Among the plethora of unanswered queries regarding hiding empty divs, I find myself unable to make any of the suggested solutions work. Hence, I am putting forth my own question. On my webpage, there is a specific section dedicated to showcasing various it ...

An error occurs when trying to load data into a grid upon clicking, resulting in an Uncaught TypeError: Unable to access properties of undefined (specifically 'dataState')

I have implemented a grid in React using a specific library, and I want to populate the grid with data fetched from an API call when the user clicks on a button labeled Fetch Products. However, I encounter an error during debugging: Uncaught (in promise) T ...

The re-rendering of my component is not triggered even after making updates to the Redux store

In my menu component, the context of the menu changes based on user input. For instance, when a user clicks on the RESERVATION button (fig 1) in the menu, the website body changes and the menu context switches to handle reservation features (fig2), which ...

Tips for sorting JSON data based on multiple attributes

http://jsfiddle.net/dy8w8r7d/ How can JSON data be sorted based on two attributes? This code snippet currently only sorts by Episode.. Purpose: arrange the data by sorting on Episode in ascending order, followed by sorting on Sequence in ascending order ...

Triggering a check event for a jQuery checkbox nested within a ul and li element

I've been working on a code snippet to handle checkbox check events: <html> <head> <style> #leftPane { width: 200px; height: 500px; border: 1px solid; float: left; } #rightPane { ...

React's nested map function is failing to display any results

My objective is to loop through nested arrays in the response data, which is an array containing other arrays. However, I am encountering an issue where the data is not being displayed for some reason. Here is an example of one item in the response: id: 5 ...

What is the best way to deactivate a submit button while an AJAX request is underway, and then reactivate it once a successful AJAX response is

I am working with the following HTML code: <form action="view_rebate_master.php" method="post"> <div class="form-group"> <label for="company_name" class="col-lg-12">Manufacturer</label> <div class="col-lg-12"> ...

What is the best way to transfer data between two JavaScript files in AngularJS using $rootScope?

In my js file named login.js, I have defined a root scope variable and assigned a value to it. Here is an example of what I have done: mainApp.controller('loginController',function($sessionStorage, $scope, $location, $window, $http, $rootScope) ...

What inspired the Angular JS Team to name their end-to-end testing tool Protractor?

Have you ever wondered why the name "protractor" was chosen for the end-to-end testing tool in AngularJS? ...

Scrolling and hovering now triggers the fixed button to toggle class seamlessly

Currently, I am attempting to modify the class of a button on my website. The initial state of the button is wide, but as the user scrolls, it should shrink in size. When hovering over the shrunken button, it should expand back to its original width. Alt ...

Isolating JavaScript Ajax codes in a Laravel 8 js file results in functionality issues

Having recently delved into the world of Ajax, I've encountered some issues. Allow me to do my best in explaining the problem at hand. Currently, I'm engaged in a Laravel 8 project. In this project, users are given the choice to select an image, ...

Having trouble getting the JavaScript slider to animate

My code works perfectly in Codepen but when I try to implement it on my website, it shows as a static image. You can view the code here: https://codepen.io/anon/pen/zPMKpv I'm using the exact same code on my website located at: Does anyone have any ...

Issue: Absence of ngResource module in Node/Express application using Angular

I am encountering this issue: Error: No module: ngResource In my index.html file, I have included a script reference like below (including ngRoute, ngSanitize, ngCookies, and a directive named angularjs.media.directive.js): <script src="/js/angular-r ...

Disregard any additional endings that do not come after a specific

I need to extract the first part of a word while disregarding any optional suffix. The prefix and suffix both consist of the same type of characters without any delimiter in between. Initially, I attempted to capture just the initial letter: m = re.searc ...