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

The Angular modal feature is specifically designed to function exclusively within the index.html

Success! My angular modal is now functioning properly. https://i.sstatic.net/CUHpL.png One thing to note is that the modal script must be placed within my index.html file for it to work: <script type="text/ng-template" id="myModalContent.html"> ...

"Return to previous page" feature

I am having difficulty figuring out how to implement the "go back" function for the page. For instance, I have pages A, B, C, and D. The possible switching between pages is as follows: A -> (B <-> C) -> A or D -> (B <-> C) -> D (w ...

Listen for the load event during an AJAX request without using jQuery's add

I have four HTML files and four corresponding JavaScript files. Each JavaScript file is externally loaded by its respective HTML file. Specifically, index.html loads javascript.js, 1.html loads javascript1.js, 2.html loads javascript2.js, and 3.html loads ...

Using jQuery to revert back to the original SRC after mouse is not hovering over an element

I've been working on a script to change the src attribute for an icon. The icon I'm loading is a different color and it's meant to notify the user about the link associated with it. Currently, I have the src changing to the second icon on h ...

How can I import a JavaScript file from the assets folder in Nuxt.js?

I have explored multiple methods for importing the JS file, but I am still unable to locate it. Can anyone guide me on how to import a JS file from the assets folder to nuxt.config.js and have it accessible throughout the entire website? nuxt.config.js he ...

Troubleshooting the deployment of a complete full-stack application on Heroku

I have been facing the challenge of deploying my full-stack chatkit messenger app from localhost to production on Heroku. I am encountering a 404 "Not Found" error and unsure about the necessary changes that need to be made in my code for it to run smoothl ...

What is the reason for utilizing the object name in the object's method rather than using "this"?

Looking at the code snippet above, you can see that store.nextId and store.cache are used in the add method. It makes me wonder why not use this instead? var store = { nextId: 1, cache: {}, add: function(fn) { if (!fn.id) { fn.id = this. ...

Is styling in React not showing up?

Currently, I am tackling a third-party pagination component in Reactjs. The npm package instructs me to include the line import "rc-pagination/assets/index.css"; in the file. However, despite injecting the index.css into the DOM using the style loader, I ...

Bird's-eye view captured by a high-angle camera

As I rotate a sphere around the z-axis, I'm looking for a way to prevent the camera from causing motion sickness by creating a stable elevated view of the sphere. How can I achieve this without the camera's movements being so jarring? If you&apo ...

What is the method for accessing cookies using JSONP?

Hello, I am trying to load a page from index.html using the following code: <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.2.min.js"></script> <script> function jsonCallback(json){ console.log(json); alert(document.c ...

Pass the PHP data back to my existing webpage for JavaScript to retrieve

I recently set up a form on my WordPress website for users to submit data. Once the form is submitted, I use AJAX to create a new post without having to reload the page. I now need to figure out how to pass the post ID, a simple integer, back to the page s ...

The onChange functionality of the Formik Field API is not compatible with a child component

I am currently facing an issue with validating a material-ui-dropzone component within the Formik Field API as a child component. When I try to upload a file, I encounter the following error: TypeError: can't access property "type", target is undefine ...

I have a task of initiating a request from JavaScript to a PHP file using an API

Seeking assistance! I have two php files named Data.php and Status.php. The task is to send a request to Data.php when data is entered in the zip field, and if the zip code is valid, then send the data to Status.php for parsing the response. Below you will ...

What is the best way to structure my POST data when conducting tests on an express API endpoint?

I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack. Currently, I am trying to test a POST API endpoint that is built using express. The node server is up ...

How to display an element using an if statement in Next.js

I am attempting to incorporate a parameter into a nextJS component that will only display if a certain condition is met. At the moment, my code looks like this: return ( <div role="main" aria-label={this.props.title} classN ...

Invoke a JavaScript function once the div has finished loading

After clicking on a radio button, I am dynamically loading a div element. I want to hide a specific part of the div once it is loaded. $(function($) { $('.div_element').on('load', function() { $('.textbox').hide(); } ...

Node JS Axios Network Error due to CORS Policy Restrictions

When attempting to make a put axios request, I encounter the following error: I have installed and enabled the CORS module in the server.js file, but it doesn't seem to be working. Additionally, there are no CORS headers in the request: In the serve ...

The concept of setting a value is not defined in JavaScript when compared to

Within my primary python script, the following code snippet is present. @app.route('/accounts/test/learn/medium') def medium(): word = random.choice(os.listdir("characters/")) return render_template('accounts/test/medium.html', word=w ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...

Botkit corner flaw

I'm having trouble updating a dependent package included in Botkit. When I run npm install on the package.json provided below, Npm alerts me that the hoek package is vulnerable. I attempted to resolve this by running npm audit fix but it did not wor ...