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

What is the best way to retrieve an object within a class?

Exploring a Class Structure: export class LayerEditor { public layerManager: LayerManager; public commandManager: CommandManager; public tools: EditorTools; constructor() { this.commandManager = new CommandManager(); this.lay ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

The search functionality in the table is experiencing a glitch where it does not work properly when trying to search with a

I created a simple mini-app with a search bar and a table displaying data. Users can enter keywords in the search bar to filter the data in the table using lodash debounce function for smoother performance. Everything works fine except for one issue - when ...

Display the initial JSON data object without the need to choose a link with the help of AngularJS

I have successfully built a webpage that displays JSON data based on the selected link. However, I am facing an issue where I need to show the first JSON data object before selecting any link (initially). Check out the Plunker demo here: http://embed.plnk ...

What is the best way to combine async/await with a custom Promise class implementation?

I've created a unique Promise class. How can I incorporate it with async/await? type Resolve<T> = (x: T | PromiseLike<T>) => void type Reject = (reason?: any) => void class CustomizedPromise<T> extends Promise<T> { ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

React - Unable to perform 'removeChild' on 'Node' object: The specified node cannot be removed as it is not a child of this node

I am encountering an issue in my React project with the following structure: <div className="App"> <BrowserRouter> <BasicLayout title={"test"}> <Routes> <Route path="/home&qu ...

Guide on incorporating one element into another with jquery

I am facing a challenge with the following code snippet: <p>Nuno</p> <p>Eimes</p> My goal is to transform it into this format: <p><a href="name/Nuno">Nuno</a></p> <p><a href="name/Eimes">Eimes& ...

Can you please explain how I can retrieve information from a Firebase collection using the NextJs API, Firebase Firestore, axios, and TypeScript?

I'm currently utilizing api routes within NextJS 13 to retrieve data from Firebase. The code for this can be found in api/locations.tsx: import { db } from "../../firebase"; import { collection, getDocs } from "firebase/firestore"; ...

Is it possible to use an angular expression as the ng-click function?

I have been searching everywhere for the answer to this question. Within my code, there is an angular object called column.addOnParams. This object includes a child element named rowClick, which can be accessed using column.addOnParams.rowClick. The val ...

Is there a reason why the JSX select element does not automatically select the option (implementing 'selected')? I'm unsure if I am overlooking something

In my HTML, I have a snippet of code that defines a custom <SelectField> component using a <select> tag like this: export default function SelectField(props) { /* PARAMETERS: - fieldname (String) - fieldID (String) - options (A ...

Benefits of utilizing minified AngularJS versions (Exploring the advantages of angular.min.js over angular.js, along with the inclusion of angular.min.js.map)

After introducing angular.min.js into my project, I encountered a problem. http://localhost:8000/AngularProject/angular.min.js.map 404 (Not Found) angular.min.js.map:1 Upon further investigation, I discovered that including angular.min.js.map resolve ...

Send a line break character as a parameter to the function

I'm currently working on a function that creates a string using a specified separator passed in as an argument. When utilizing the \n character as a separator, the output doesn't match my expectation. let concatenate = function(first, secon ...

No Backend Detected for Tensorflow.js in Node

I've been attempting to develop a Discord bot that utilizes the @tensorflow-models/qna library, but I've hit a roadblock for the past 4 hours. Every time I run the script below: const qna = require('@tensorflow-models/qna'); (async () ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Requesting data from a server using JavaScript/Ajax/Flash technologies over

Here is the code snippet I am currently using: swfobject.embedSWF("/Content/open-flash-chart.swf", "my_chart", "750", "300", "9.0.0", "expressInstall.swf", ...

The data is not appearing in the Vuetify data table

I have encountered an issue with the Vuetify data table where it is not displaying any data. Even though it shows that there is 1 row out of 1 displayed, the table body remains empty. Below is my component code: <template> <v-data-table :hea ...

Axios failing to transmit cookie information, despite setting withCredentials to true

Exploring the capabilities of React and Express to handle requests while including cookies. The communication between client-side and server-side is successful, however, the cookies are not being transmitted. On the client-side: import axios from 'axi ...