Can regex matching characters be made easier to understand?

I am working on creating an ECMAScript (JavaScript) flavored regex to evaluate the complexity of my password based on specific criteria:

    Characters Used          Password Strength Length
   ABC  abc  123  #$&      WEAK  ...
1   x                      1-5   ...   
2        x                 1-5
3             x            1-7
4                  x       1-5
5   x    x                 1-4   
6   x         x            1-4
7   x              x       1-4
8        x    x            1-4 
9        x         x       1-4       
10            x    x       1-4     
11  x    x    x            1-4           
12  x    x         x       1-3   
13  x        x     x       1-4           
14      x    x     x       1-4  
15  x   x    x     x       1-3     

Therefore, passwords like 2, ABCD, 0123456, abCd, aA#, etc. should be considered weak. Passwords that are longer while meeting the specified criteria e.g., 012345678, aA1#, should not.

My current intricate regex pattern (organized by groups according to the above table) looks something like this:

/^(([A-Za-z&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,3})|([a-z0-9&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,4})|([A-Z0-9&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,4})|([a-zA-Z0-9]{1,4})|([a-z]{1,5})|([A-Z]{1,5})|([0-9]{1,7})|([&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,5}))$/

Matches rows in the above table: 12

/([A-Za-z&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,3})/

Matching rows: 14, 9

/([a-z0-9&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,4})/

Matching rows: 13, 10, 7

/([A-Z0-9&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,4})/

Matching rows: 11, 8, 6, 5

/([a-zA-Z0-9]{1,4})/

Matching rows: 2

/([a-z]{1,5})/

Matching rows: 1

/([A-Z]{1,5})/

Matching rows: 3

/([0-9]{1,7})/

Matching rows: 4

/([&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,5})/

Is there a way to reuse the special characters I defined inside []

[&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]
, so that I don't have to list them out within each individual group?

Answer №1

Is there a way to reuse specified special characters inside [] without rewriting them in every group?

No, you cannot do this with a regular expression literal.

However, you can achieve this using the RegExp constructor. To avoid escaping backslashes, you can utilize String.raw like so:

const chars = String.raw`[the chars]`;
const rex = new RegExp(String.raw`^...${chars}...${chars}...$`);

You can even create a custom tag function for this purpose, as demonstrated below (excerpt from Chapter 10 of my latest book; refer to my profile for more information):

const createRegex = (template, ...values) => {
    const source = String.raw(template, ...values);
    const match = /^\/(.+)\/([a-z]*)$/.exec(source);
    if (!match) {
        throw new Error("Invalid regular expression");
    }
    
    const [, expr, flags = ""] = match;
    return new RegExp(expr, flags);
};

With this custom function, you can simplify regex creation like this:

const chars = String.raw`[the chars]`;
const rex = createRegex`/^...${chars}...${chars}...$/`;

Answer №2

If you are utilizing a regex engine like Perl or Ruby, leveraging subroutines can help you achieve the desired results to a considerable extent. Subroutines essentially entail repeating patterns within a regex.

You might be familiar with backreferences, but it's important to note that subroutines differ from backreferences. With backreferences, the matched content of a captured group is used, whereas with subroutines, the pattern matching is reiterated.

Let's consider an example:

  • Sample string: abcd-defg
  • Regex in Ruby:
    /(?<dd>[a-z]+)-\g<dd>/
    . This will result in a successful match.
  • The \g<dd> section represents the subroutine call in Ruby for the group named dd. (The syntax may vary depending on the regex engine you are using.)

For more information, you can refer to the following resources:


In your specific scenario, naming each group when it initially appears in the regex and then referencing it as a subroutine subsequently could be beneficial. For instance:

  • [A-Z] could be denoted as A
  • [a-z] could be represented as a
  • [0-9] could be termed as n
  • and the special character set as s (assuming correct pattern identification)

Therefore, the pattern for 12

/([A-Za-z&*@\^}\]\\):,$=!><–{[(%+#;\/~_?.]{1,3})/
could transform into

/((\g<A>|\g<a>|\g<s>)){1,3})/

Meaning, A OR a OR s repeated 1-3 times.

And the pattern for 11, 8, 6, 5 /([a-zA-Z0-9]{1,4})/ would evolve into

/((\g<a>|\g<A>|\g<n>)){1,4})/

Signifying, a OR A OR n repeated 1-4 times.

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

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

How can you efficiently manage Access & Refresh tokens from various Providers?

Imagine I am allowing my users to connect to various social media platforms like Facebook, Instagram, Pinterest, and Twitter in order to use their APIs. As a result, I obtain access tokens for each of these providers. Based on my research, it seems advisa ...

How to implement dynamic aggregate functions with parameters in Express and Mongoose

I have implemented an aggregate function in mongoose to fetch some data, with a static implementation. app.get("/male",function (req,res) { Record.aggregate([ { $match: {"gender": "male"} }, { $group:{ _i ...

Encountering an issue with postman where properties of undefined cannot be read

I am facing an issue while trying to create a user in my database through the signup process. When I manually enter the data in the create method, it works fine as shown below: Note: The schema components are {userName:String , number:String , email:Stri ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...

Guide on integrating angular-schema-form into an Ionic 2.0 project using typescript

Recently, I embarked on creating an app with Ionic from scratch and decided to integrate the framework. While I faced no issues executing the example on a webpage, I encountered difficulties when attempting to do so with Ionic. To kickstart the project, ...

Is there a jQuery function that can produce repeated output and append content with each successive click?

Attempting to implement a dynamic searchbar with various parameters has led me to explore using jQuery to load and clone the searchbar file in order to append it to the body dynamically. I have made several attempts to modify selectors without achieving t ...

Unveiling Fresh URLs within an iFrame

Here is the current situation: www.mywebsite.com/Pagex.html - On this page, there is an iFrame with a default URL (src) from a different domain than the host page (Pagex.html). The code inside the iFrame is a user input form with a submit button. Upon su ...

The function react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_4__.jsxDEV(...) is not recognized

For my react-redux project, I utilized json-server as the server for managing orders. The status of each order is saved in the state within UiReducer and is then accessed in the "OrderStatusPage". The current NODE_ENV configuration is set to "development". ...

Tips for Retrieving a JavaScript Variable's Value in JSP

In my JSP file, I have implemented dynamic rows of textboxes using JavaScript. Now that I have input values into these fields, how can I retrieve those values in my result JSP page? ...

Tips for clearing a saved password in a browser using Angular.js and Javascript

There is an issue with the password and username fields in my Angular.js login page. When a user clicks on the 'remember me' option in their browser after logging in, the saved username and password are automatically displayed in the respective f ...

Ways to remove code from production during build process?

Is there a way to omit typescript code from getting bundled by webpack during build process? Let's say I have the following line of code in my app.ts file (a nodejs application): const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa ...

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

Implementing the jquery mobile data-native-menu feature in a select element dynamically generated from jeditable

Greetings! I have encountered an issue where the data-native-menu="false" instruction works correctly when directly placed in a select element, but doesn't work when added to a select generated by JavaScript (using the Jeditable plugin). You can view ...

Guide on creating a square within an element using JavaScript

After conducting thorough research, I find myself unsure of the best course of action. My situation involves a Kendo Grid (table) with 3 rows and 3 columns. Initially, the table displays only the first column, populated upon the page's initial load. S ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...