Is there a regular expression that can match any permutation of three digits?

Is it possible to create a regular expression that can determine if a string contains at least 3 digits, regardless of their order?

(I would appreciate seeing the exact regex solution for this.)

For example:

abk2d5k6 //3 digits
abk25k6d //also has 3 digits

My attempts so far:

.+?(?=\d){3}

Thank you.

(Please provide only regular expressions for learning purposes.)

Answer №1

If you're looking to learn more about this topic, I highly recommend diving into this extensive tutorial.

Alternatively, when it comes to JavaScript regex, the code snippet for ensuring at least three digits could resemble something like:

/^(?:\D*\d){3}/

On the other hand, if your goal is to verify exactly three digits are present, you might use:

/^(?:\D*\d){3}\D*$/

In these expressions, \D represents any non-digit character, * indicates zero or more occurrences of that character, \d signifies any digit character, {3} repeats the subpattern thrice, while ^ and $ respectively denote the start and end of the string.

Answer №2

Another way to achieve the same result is by using the following code:

str.match(/\d/g).length >= 3

This method is straightforward and effectively communicates the purpose without the need for a complex regular expression.

Please note that this solution may not be optimized for speed performance.

Answer №3

After considering your request for "at least" three digits, the solution doesn't have to be overly complex. Here is a simple regex that should suffice:

/\d.*\d.*\d/

This pattern matches a digit followed by zero or more characters, then another digit, and so on. Since I haven't anchored either end, it allows for any number of characters before and after the digits.

console.log(!!"abk2d5k6".match(/\d.*\d.*\d/));  // true
console.log(!!"abk25k6d".match(/\d.*\d.*\d/));  // true
console.log(!!"abkd5k6".match(/\d.*\d.*\d/));   // false (A digit was removed)
console.log(!!"abk2k6d".match(/\d.*\d.*\d/));   // false (A digit was removed)

Alternatively, you can use:

/(\d.*){3}/

console.log(!!"abk2d5k6".match(/(\d.*){3}/));  // true
console.log(!!"abk25k6d".match(/(\d.*){3}/));  // true
console.log(!!"abkd5k6".match(/(\d.*){3}/));   // false (A digit was removed)
console.log(!!"abk2k6d".match(/(\d.*){3}/));   // false (A digit was removed)

As suggested by m.buettner in the comments, instead of using ., you can utilize \D (not a digit):

/\d\D*\d\D*\d/

or

/(\d\D*){3}/

display(!!"abk2d5k6".match(/\d\D*\d\D*\d/));  // true
display(!!"abk25k6d".match(/\d\D*\d\D*\d/));  // true
display(!!"abkd5k6".match(/\d\D*\d\D*\d/));   // false (A digit was removed)
display(!!"abk2k6d".match(/\d\D*\d\D*\d/));   // false (A digit was removed)

display(!!"abk2d5k6".match(/(\d\D*){3}/));  // true
display(!!"abk25k6d".match(/(\d\D*){3}/));  // true
display(!!"abkd5k6".match(/(\d\D*){3}/));   // false (A digit was removed)
display(!!"abk2k6d".match(/(\d\D*){3}/));   // false (A digit was removed)

In summary, there's no need for anchors when seeking an "at least" match.

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

Creating a form with multiple checkboxes using Material-UI components where only a single checkbox can be selected

Creating a simple form using Material-UI with checkboxes to select one option and push data to the backend on submit is the goal. The Form component structure includes: multiple options represented by checkboxes only one checkbox can be selected at a time ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...

Utilize Javascript to acquire the redirected URL

Seeking assistance with making a GET call to an API endpoint that redirects me. I have enabled CORS to access the Location, but struggling to find a way through Ajax or Fetch to retrieve only the Redirect URL. Any help would be highly appreciated. ...

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

We have encountered an issue with the syntax in the code: ajaxsample/update_agenda. It seems to be an unrecognized expression according to

Here's the code for updating my controller: public function update_agenda() { $id= $this->input->post('did'); $this->load->model('agenda_model'); $data = array ( ...

How can I remove a row from an MVC webgrid using an ajax call?

Within my MVC Razor view, I have a partial view containing webgrid data. My goal is to include an action link to delete a specific row of data. To accomplish this, I crafted the following JavaScript function: function delMeal(pid) { if (confirm("Do yo ...

Divide the array object based on the "@" symbol

i am in possession of the following array object let old_array = { "valone": "facebook", "notification": "new message! @[email protected] @[email protected]" } i aim to extract all users with @ sign into a new array like displayed below le ...

Implementing OutlinePass from Three.js in React

I am attempting to implement the Post-processing Outline Thee.js example in a React environment with server-side rendering. The challenge I am facing revolves around lines 47 and 280 in the example: <script src="js/postprocessing/OutlinePass.js">< ...

How can one implement a matrix transformation and establish it as the default state in ThreeJS?

I am working with a group of THREE.Mesh objects and my objective is to apply a rotation using the code snippet group.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI / 2) );. Afterwards, I want to set this resulting matrix as the default state for t ...

Check the validity of your JavaScript files with our convenient online tool!

Is there a website or online tool available to validate the syntax of JavaScript code in a file? I am experiencing problems with Internet Explorer 7 while running JavaScript, so I want to make sure my JavaScript file is valid. ...

Using React Router can sometimes lead to an issue where the React components are

My server side rendering is set up for performance, but I am encountering discrepancies between the client and server renderings. The client initially renders <!-- react-empty: 1 --> instead of components, which leads to a different checksum. As a re ...

Leveraging the power of the underscore library within the WordPress

I'm currently utilizing the underscore library for handling arrays. I have included the library using the code snippet below in my functions.php file add_action( 'wp_enqueue_scripts', 'jt_enqueue_scripts' ); function jt_e ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

What is the process of updating values in an object that is part of an array?

I am currently facing an issue where I am attempting to implement an edit function to replace text and dates. While I have managed to successfully update the text using the DOM, the edited values revert back to their original form upon page refresh. I susp ...

Transforming a text into a vNode in VueJS

I recently encountered a situation where I had a string stored in the database that looks something like this: Lorem #ipsum dolor sit amet, #consectetur adipiscing elit, sed do #eiusmod tempor incididunt ut labore et dolore magna aliqua. Within the string ...

Is there a way to retrieve the ref value from another component file?

Below is the code found in App.vue: <script setup> import Nav from "./components/Nav.vue"; </script> <template> <Nav/> </template> ................................................................... Now, take a ...

Is there a way to ensure that GIFs in jQuery Mobile always start from the beginning?

My cross-platform mobile app built with jQuery Mobile is a small quiz application. After each correct or wrong answer, I display a 3-second GIF. Currently, I have set up the code to show the GIF for 3 seconds before moving on to the next page: else if ($. ...

What is the best way to reset the state in React prior to the render being called?

Whenever I click on a copy icon, a popup is displayed. This happens because the state "showPopup" is set to true upon clicking the copy icon, and the render function recognizes this and shows the popup. The popup will close automatically if I click anywher ...

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...