Pattern to prevent consecutive hyphens and identical digits next to one another in a series

Here is a regular expression that can validate all numbers not being the same even after a hyphen:

^(\d)(?!\1+$)\d{3}-\d{1}$

For example, in the pattern:

0000-0 would not be allowed (all digits are the same)
0000-1 would be allowed
1111-1 would not be allowed (all digits are the same)
1234-2 would be allowed

Answer №1

By utilizing back references, solving this issue becomes quite simple (and fortunately, js regex supports this).

The following regex only identifies the invalid inputs.

^(\d)\1+-\1$

See Regex Demo

^     - Start of line
(\d)  - create a capturing group with the first digit (essential for the next step)
\1+   - back reference to group 1 (\d+) and match it one or more times
-     - match a hyphen
\1    - back reference to group 1
$     - end of line 

On the JS side, if the regex matches, then you can determine that the input was invalid.

const inputs = [
'0000-0',
'0000-1',
'1111-1',
'1234-2'
];

const regex = /^(\d)\1+-\1$/;

inputs.forEach(item => {
 if (item.match(regex)) {
    console.log(item + ' - INPUT NOT ALLOWED')
 } else {
    console.log(item + ' - VALID INPUT')
 } 
});

Check JS Demo

EDIT

To accommodate the new requirements, simply combine the regex with another regex checking the total length.

^(?:(\d)\1+-\1$|.{7,})

See Demo

And if you are working with Java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        // String to be scanned to find the pattern.
        String[] lines = {
                "0000-0",
                "0000-1",
                "1111-1",
                "1234-2",
                "1234567-2",
                "1234-26"
        };

        String pattern = "^(?:(\\d)\\1+-\\1$|.{7,})";
        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        for(String line : lines) {
            System.out.print(line);
            Matcher m = r.matcher(line);
            if (m.find()) {
                System.out.println(" - INVALID");
            }else {
                System.out.println(" - VALID");
            }
        }
    }
}

** Output **

0000-0 - INVALID
0000-1 - VALID
1111-1 - INVALID
1234-2 - VALID
1234567-2 - INVALID
1234-26 - INVALID

Process finished with exit code 0

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

Utilizing jQuery for AJAX-Based Deletion of Records

Hey, I stumbled upon a code snippet that allows me to delete a row from my database using Ajax. However, there seems to be an issue where the table that should disappear when deleted is not working properly. Here is the JavaScript code: <script type=" ...

How to stop the HTTP Basic Auth popup with AngularJS Interceptors

In the process of developing a web app using AngularJS (1.2.16) with a RESTful API, I encountered an issue where I wanted to send 401 Unauthorized responses for requests with invalid or missing authentication information. Despite having an HTTP interceptor ...

The code is triggering IE 8 to switch to compatibility mode resembling IE7

I have created a custom javascript function that generates a pop-up, and I am invoking this function in my code. However, every time I click the button, the browser switches to IE 7 compatibility mode and the pop-up appears behind the button. Below is my ...

Capture data from Ajax requests and store them in PHP variables

When setting up a DDBB Insert using $.ajax, I encountered an issue. $(document).on('click','.submitMessage', function(){ content=$('textarea').val(); img=$('#messageImg').val(); stdMsg=$('.ms_stdMsg ...

Display radio options when clicked upon

I am in the process of creating a set of radio buttons that will be utilized for capturing values to generate a subscription/modal checkout. My current situation involves having the radio button options visible. However, I aim to achieve a functionality wh ...

Utilizing Redux with React to fetch and handle JSON data from given API endpoint

The assignment I'm working on requires us to fetch JSON data from a specific endpoint called url and display it in an Excel-like table using React, Redux, and Redux-Thunk. I successfully managed to retrieve and display the data in a table by utilizin ...

After the recent update to version 4.2.0 of @material-ui/core, unexpected react hook errors have been

Currently, I am working on an electron application that utilizes react and material-ui. Recently, I made the decision to update material-ui to version 4.2.0. As a result of this update, two lines were added to my dependencies in the package.json. "@materi ...

Adding a JSON array to all JSON objects in JavaScript: A step-by-step guide

Here is a JSON Object that I am working with: { "status": "CREATED", "overrides": { "name": "test_override" }, "package_name": "test", "name": "app1", "defaults": { "job": { "example": { "executors_num": "2", "fr ...

Check if the user is null using React's useEffect hook and then perform a

I am currently working on implementing a protected route in Next JS. I have included a useEffect to redirect to the sign-in page if there is no user detected. const analytics = () => { const { userLoaded, user, signOut, session, userDetails, subscri ...

Adding JSON to the data attribute within a set of DOM elements

I am in the process of developing a website dedicated to recipes, where I am using a Mustache.js template to load recipe information from a JSON file. The structure of my JSON file is as follows: { "recipes":[ {"name": "A", preparationTime: "40min", "serv ...

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...

JavaScript and Ajax are functioning properly in Mozilla Firefox, however there seem to be some compatibility issues with Google Chrome

I have a form that serves the dual purpose of registration and login, and I am using JavaScript Ajax to submit it. While it works smoothly in Mozilla Firefox, it fails in Chrome and IE. The goal is to execute an AJAX and PHP script that checks the databa ...

Utilizing Vue.js to incorporate the isActive property to the class name within a v-for loop, along with implementing dynamic class names

I am currently using a loop to iterate through some data in my store.js file, and everything is functioning as expected. However, I would like to add a condition to check if the Vue instance is active before applying a specific class to the polygon element ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Guide on implementing themes to HTML within the append() function

I am currently working on a project where I need to dynamically add HTML tags using JavaScript. However, I have noticed that the themes or styles are not being applied to the newly added elements within the append method. In my HTML file, I am using jQue ...

Issue with using jQuery and parseDouble

I have been dealing with an AJAX request that retrieves a JSON object containing multiple values, each with two decimal points. However, the issue is that when these values are returned as part of the JSON, they are in string format. My goal is to perform ...

Looking for a way to avoid hard coding your Java program? Consider using a property file. However, struggling to implement it with several different xpaths?

Task: Obtain a recent monthly report from the website. Monthly Report: October 2015 Unconventional Wells The following is the setup: config.properties: #browser browser=http://www.depreportingservices.state.pa.us/ReportServer/Pages/ReportViewer.aspx?%2 ...

What is the best way to customize material components using styled components?

What is the best approach to override material components with styled components, considering that material-ui component classes typically have higher priority than styled-component classes? Is using the !important flag the most effective solution? <bu ...

Definition in Typescript: The term "value is" refers to a function that takes in any number of arguments of

export function isFunction(value: any): value is (...args: any[]) => any { return typeof value === 'function'; } What is the reason behind using value is (...args: any[]) => any instead of boolean ? ...

Is there a way to track whether a user has logged into the Google Chrome browser using cookies?

While the LSID cookie can indicate if a user is logged into a Google account, it cannot be reliably used to determine if someone is signed into the Chrome browser because it may also appear when a person is signed into Gmail without being signed into Chrom ...