Regular expression for precise numerical values of a specific magnitude (any programming language)

I have been searching for a solution to what I thought was a common problem but haven't found one yet.

What I need is a regular expression that will fail on a specific number of significant figures (a Max), but pass for fewer than the Max. It should also work with both dot or comma (French) decimal separators.

For 15 significant figures, the following values should pass:
0
0.00
1
-1
1.23456789012345
10.2345678901234
12.3456789012345
-123.4
-12.34
-1,33
-1.33
-123456789012345
-1234567890123450
-12345678901234.50
12345678901234.50
123456789012345.00

// These values should fail:
-1234567890123456
-12345678901234.56
12345678901234.56
123456789012345.60
1.234567890123456
12.34567890123456
123456789012340.6
123456789012300.67
123456789012300000000000.67
10000000000010000000001000010000000001.22

I understand that I need to use negative lookaheads and have come close with this so far:

^(?!(?:.*?[1-9]){15,})([-+]?\s*\d+[\.\,]?\d*?)$

https://regex101.com/r/hQ1rP0/218

However, as you can see, the last few still pass. Any suggestions?

Answer №1

Code

If you are looking for actual scientific notation, where leading zeros matter before the decimal symbol, here is the regex pattern to use:

^-?(?=\d{1,15}(?:[.,]0+)?$|(?:(?=.{1,16}0*$)(?:\d+[.,]\d+)))‌.+$

However, if you need a regex that works for cases with leading zeros regardless of decimal position, this alternative will work:

You can see this regex in action here

^-?(?=\d{1,15}(?:[.,]0+)?0*$|(?:(?=.{1,16}0*$)(?:\d+[.,]\d+)‌​)).+$

Explanation

  • ^ This asserts the position at the start of the line
  • -? Match zero or one hyphen character literally
  • (?=\d{1,15}(?:[.,]0+)?0*$|(?:(?=.{1,16}0*$)(?:\d+[.,]\d+)))
    Positive lookahead ensuring what follows matches the following
    • \d{1,15}(?:[.,]0+)?0*$ Option 1
      • \d{1,15} Matches between 1 and 15 of any digit character
      • (?:[.,]0+)? Matches a decimal symbol ,. followed by one or more 0s literally, but either zero or one time
      • 0* Matches any number of 0s literally
      • $ Asserts the position at the end of the line
    • (?:(?=.{1,16}0*$)(?:\d+[.,]\d+)) Option 2
      • (?=.{1,16}0*$) Ensures what follows matches the following
      • .{1,16} Matches any character between 1 and 16 times
      • 0* Matches any number of 0s literally
      • $ Asserts the position at the end of the line
      • (?:\d+[.,]\d+) Matches the following
      • \d+ Matches any digit between 1 and unlimited times
      • [,.] Matches a decimal character
      • \d+ Matches a digit between 1 and unlimited times
  • .+ Matches any character one or more times
  • $ Asserts the position at the end of the line (not essential but helps with readability)

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

NodeJS making seven successful Ajax requests

I'm delving into the world of JavaScript, NodeJS, and electron with a goal to create a presenter-app for remote control over powerpoint presentations. My setup involves an electron server structured like this: const electron = require('electron ...

When an array object is modified in Vue, it will automatically trigger the get method to validate any

One of the challenges I am facing is related to a button component that has a specific structure: <template> <button class="o-chip border-radius" :class="{ 'background-color-blue': theValue.isSelected, ...

The appearance of Recaptcha buttons is unattractive and seemingly impossible to

Let me start by saying that I have already looked into the issue of "Recaptcha is broken" where adjusting the line-height was suggested as a solution. Unfortunately, that did not work for me. After implementing Google's impressive Recaptcha on my web ...

Adjust the height of the container div for the carousel according to the length of the text displayed

My image carousel features description content positioned on the right for wide-screen windows. However, I want the description to shift below the images when the browser window reaches a certain breakpoint. The challenge I am facing is that the height of ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

Customizing the language parameter for the apply button script on LinkedIn

Our company's website features the AWLI button which allows users to apply for jobs using their LinkedIn profile. <div name="widget-holder"> <script type="text/javascript" src="https://www.linkedin.com/mj ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

Neither the context nor props contain the element 'store' that you are searching for

Just stepping into the world of React can be overwhelming, but I'm determined to get my page to render properly: import React, { Component } from "react"; import { connect } from "react-redux"; import Header from '../components/Header'; imp ...

What is the best way to retrieve a default property from a JavaScript literal object?

In the following example, a JS object is created: var obj = { key1 : {on:'value1', off:'value2'}, key2 : {on:'value3', off:'value4'} } Is there a clever method to automatically retrieve the default valu ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

The page refreshes automatically when the search icon is clicked, but the ajax method does not trigger the page reload

Whenever I click on the search-box <a>, the JavaScript is triggered but doesn't execute the ajax method filter_data_guide_specs(). Instead, the page automatically reloads and fails to read the JS code. HTML <div class="form-group"> < ...

Is it possible to establish a default route in Next.js?

Is it possible to set up default routes in Next.js so that all routes, or a specific list of routes, will automatically navigate to a designated page? My project involves using Next.js to create the marketing website, as well as the sign-up and sign-in pr ...

Can someone explain the function of statements such as (function () { // code; }.call(this)); within a JavaScript module?

By utilizing the Function.prototype.call() method, it becomes possible to create a function that can be applied to various objects. I delved into the code of , which had been minified and required to be un-minified for examination. The structure of the co ...

Using VueJS to determine if a certain string includes a specific substring within an if-statement embedded within a v

I am aiming to verify if the link in a json object contains 'http'. If it does, I want to assign a target='_blank' attribute to the v-btn. The link could also be something like #test. Currently, this is how I am attempting to achieve i ...

Looking to modify the contents of a shopping cart by utilizing javascript/jQuery to add or remove items?

I'm dealing with a challenge on my assignment. I've been tasked with creating a Shopping Cart using Javascript, HTML5, and JQuery. It needs to collect all the items from the shop inside an Array. While I believe I have most of it figured out, I a ...

Ways to unzip binary information in node.js

Once I have decoded my data from base 64 to binary, my next step is to unzip this information. In my project, I am using node.js instead of PHP, which has a convenient gzdecode() function for decompressing data. However, with node.js, I am unsure of how t ...

Retrieving information from a virtual document in a 'pre' save hook using Mongoose

Seeking help with utilizing data from a recently created document to update a value using a 'pre' hook. An example of the model being used: ... title: { type: String, required: true }, company: { type: mongoose.Schema.ObjectId, ref: &ap ...

Having trouble with an endless GET request loop in NextJS 13 while utilizing the Next-Auth middleware. Experiencing difficulties fetching the RSC payload

UPDATE: The issue has been identified! It seems that the bug is caused by using the beta turbopack. I have reported this problem and we are awaiting a resolution. Query: I recently delved into a project in NextJS 13 with the new app directory setup. Afte ...

Looking for assistance in reducing the vertical spacing between divs within a grid layout

Currently, I am in the process of developing a fluid grid section to showcase events. To ensure responsiveness on varying screen resolutions, I have incorporated media queries that adjust the size of the div elements accordingly. When all the divs are unif ...