Matching only digits in Javascript using Regex when they are not immediately preceded or followed by letters

Looking to find digits but not when they are part of words (using JavaScript).

The examples that should yield a match:

1
1,2
1.5-4 (matches 1.5 & 4 separately)
(1+3) (matches 1 & 3 separately)
=1;

The following examples should NOT produce a match:

FF3D
3deg

I attempted to use negative lookahead with this pattern:

(?![A-Za-z]+)([0-9]+[\.|\,]?[0-9]?)
, but it did not work as intended.

What is the best approach to addressing this issue? Thank you.

Answer №1

I need help finding numbers in a string, but only if they are not part of a word.

You can achieve this using look arounds in your regular expression:

\b\d*[,.]?\d+\b
  • \b represents a word boundary

Check out the RegEx demo here

Answer №2

Update for 2021:

Due to the significant growth in lookbehind support, it is recommended to use a lookbehind-based solution like this:

/(?<!\w)\d*[.,]?\d+(?!\w)/gi         # ASCII only
/(?<!\p{L})\p{N}*[.,]?\p{N}+(?!\p{L})/giu  # Unicode-aware

You can see the regex demo here. Keep track of lookbehind and Unicode property class support on this page.

More Information

  • (?<![a-z]) - there should not be any ASCII letter (or any Unicode letter if using \p{L}) immediately to the left
  • \d*[.,]?\d+
  • (?![a-z]) - there should not be any ASCII letter (or any Unicode letter if using \p{L}) immediately to the right.

Original Answer

If you want to match standalone integer or float numbers with dot or comma as decimal separators, you can use the following pattern:

/(?:\b\d+[,.]|\B[.,])?\d+\b/g

Check out the regex demo here. The key point is that you cannot use a word boundary \b before a . because it will exclude matches like .55 (only 55 will be matched).

Details:

  • (?:\b\d+[,.]|\B[.,])? - either of these alternatives:
    • \b\d+[,.] - a word boundary (must include a non-word character before or start of string), then 1+ digits, followed by a . or ,
    • | - or
    • \B[.,] - a position that is not a word boundary (only includes a non-word character or start of string) followed by a . or ,
  • \d+ - 1+ digits
  • \b - a word boundary.

const regex = /(?:\b\d+[,.]|\B[.,])?\d+\b/g;
const str = `.455 and ,445 44,5345 435.54 4444
1
1,2
1.5-4
(1+3)
=1;

FF3D
3deg`;
console.log(str.match(regex));

If you also need to add support for exponents, you can use this pattern:

/(?:\b\d+[,.]|\B[.,])?\d+(?:e[-+]?\d+)?\b/ig

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

Encountering the error message "Attempting to access properties of undefined (specifically 'map')". Despite having the array properly declared and imported

I am facing an issue while trying to iterate through an array and display names for each person. Despite declaring the array properly, it is returning as undefined which is causing the .map function to fail. Can you help me figure out where I am making a m ...

A method for modifying the key within a nested array object and then outputting the updated array object

Suppose I have an array called arr1 and an object named arr2 containing a nested array called config. If the key in the object from arr1 matches with an id within the nested config and further within the questions array, then replace that key (in the arr1 ...

Unlock the encrypted information in the blockchain

I've been working on encrypting and decrypting values using Node's built-in crypto module. I found a helpful tutorial that showed me how to encrypt the data, but it didn't provide any sample code for decryption. When I tried using code from ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

The reveal/conceal feature will not reveal all elements at the outset

I've been working on implementing a show/hide elements filter. However, I'm facing an issue where all elements that are supposed to display initially are hidden instead. Additionally, the 'active' class is not being properly removed or ...

Illuminate specific areas of a mapped image upon hovering over text on a webpage

Scenario: There is an image on the page with various mapped areas. A list of text elements is also present on the page. Desired functionality: Hovering over different text items in the list should result in highlighting corresponding areas on the mappe ...

Is there a way to alter the timestamp on comments in a React Native app, similar to Instagram's functionality, using dayjs?

I am currently working on a project using react native in combination with dayjs library. My goal is to compare the timestamp of when a comment was written with the current time, and then display this compared time using console.log() with the help of day ...

"Waiting for results with Node.js and Mongo DB is like trying to catch a

I am currently working on developing a Web Api using NodeJs and MongoDB. One issue I have encountered is that my await statements are not being awaited, leading to unexpected behavior in my code. Code async find_nearby_places(lng, lat, tag, maxDistanc ...

Ways to create a smooth transition in element height without a known fixed target height

Is it possible to create a smooth height transition for an element when the target height is unknown? Replacing height: unset with height: 100px allows the animation to work, but this presents a problem as the height needs to be based on content and may v ...

Is it possible to pass the chart type as a property when using vue-chart.js?

Is it possible to pass the chart type as a property with vue-chart.js? I would love to see some example source code. Can you please provide guidance on this? ...

Building a dynamic search feature using Ajax and PHP to transfer search results to a PHP variable or display as plain text

I designed a form that allows users to input orders with various details into the database. One of the fields in this form is labeled Client, where users have the option to either create a new client or select an existing one. To facilitate the selection ...

Setting up flowplayer for multiple div elements: a tutorial

I have a collection of videos and I am trying to set up the player for each div that holds a video. When constructing the divs in my JavaScript code, it looks like this: <div id="player+{{$index}}"></div> // The "player" + index is generat ...

Activate PHP using javascript

My PHP script is designed to capture a user's IP address, current webpage, screen resolution, and Date/Time when they visit my website. To implement this tracking functionality on another website, I plan to insert the following line of code: <scr ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Creating a JSFiddle with sprites using source and image files from Github with THREE.JS - a step-by-step guide

Greetings! I am currently working on creating a JSFiddle based on the official THREE.js HUD Sprites example. However, I am facing an issue where the sprite images do not seem to load or apply using the URLs specified in the original file:- //... URL' ...

Transforming JSON in Node.js based on JSON key

I am having trouble transforming the JSON result below into a filtered format. const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, ...

Trying out an alert using HtmlUnit

I have grasped the concept somewhat from the instance of "Watching for 'alerts'" on this website: HtmlUnit- Javascript Tutorial. Being new to .NET, the functionality of Collections.singletonList is unclear to me, and after some research, I discov ...

When the Add button in AngularJS is clicked, a new popup page should appear by concealing the parent page

I am currently working on a project that involves using the AngularJS/Breeze framework within the HotTowel Template. One of the requirements I have is to include a button/link labeled "Add" on the parent.html page. When this button is clicked, it should t ...

Assign the variable of one function to another function

I have a collection of buttons with usernames as values (such as jason, chan, brad, etc.). When a user clicks on a button, it is moved to a specific div. For example: <input type="button" onClick="nano();" id="name1" class="names" name="jason" value=" ...

"Enhance your website with powerful AJAX functionality using the October CMS

Can you help me troubleshoot this AJAX error I'm encountering when trying to call an AJAX action? The error message is indicating an 'Invalid handler name.' The correct format for the handler name should be "onEvent" I am attempting to u ...