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

What could be causing my Bootstrap datepicker to malfunction?

A while ago, my Bootstrap datetimepicker component was functioning perfectly in my code. However, it has suddenly stopped working and I am seeking assistance to get it running smoothly again. Below is the HTML code snippet: <script src="https://cd ...

Verifying conditions in an AJAX-based upload system using JavaScript

Recently, I was working on implementing a JavaScript/AJAX upload system with a progress indicator based on a tutorial. The process went smoothly, and I even managed to include a CSS progress bar for visual representation. However, I encountered a hurdle th ...

Wrap a collection of text lines with a leading indentation of 4 spaces

I am looking to wrap all the lines within a <pre> tag that start with 4 spaces. What have I attempted so far? ^[ ]{4}(.*)(?!=^[ ]{4}) DEMO Input: Here is the code: String name = "Jon"; System.out.println("Hello "+name); output: Hello ...

What is the process for adding content to a JSON object?

I may have a simple question, but I'm new to backend development and I'm trying to figure out how to post in JSON format. Here is the JSON schema I am working with: email: { type: String, unique: true, lowercase: true, required ...

Conceal the div element if the value is either undefined or empty in AngularJS

I am experiencing an issue where I get 2 different values when I use console.log($scope.variable). The values shown are undefined and ''. Based on this value, I need to hide a div. Here's what I have tried: <div ng-hide="$scope.variable ...

Experience the thrill of Morphia MongoDB: You have already defined the Filter type

Upon attempting to start a Play Java application with Morphia for MongoDB, I encounter the following stack trace due to the recompilation of the Filter type that is already compiled: An unexpected Internal Server Error (500) occurred while making a requ ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

Top eCommerce frameworks optimized for Web2 and SaaS integration

Are there any payment and eCommerce frameworks that can seamlessly integrate with a REST-based application right out of the box? My server is Java-based, but I've found limited options in this area. I'm open to wrapping my interface with another ...

Attempting to modify the key values within an object, however, it is mistakenly doubling the values instead

I'm encountering an issue when trying to update key values within an object. It seems to be adding duplicate values or combining all values together instead of assigning each name a specific language slug. I can't figure out where I'm going ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Choose an element that has been generated dynamically using jQuery

Here is an example HTML table to work with: <table id="#myTable"> <tr id="#row123"><td>Content</td></tr> </table> To insert a new row using jQuery, you can use the following code: $('#myTable').prepend(&ap ...

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

Is there a way to delete highlighted text without using execCommand and changing the font color

With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted. ...

Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component: <template> <div> <Nav :data="data" /> </div> </template> <script lang="ts"> // ... imports removed for clarity @Component({ components: { Nav: () => import('@/components/Nav.vue&ap ...

Creating an npm module using an external JavaScript API script

I am currently in the process of creating an npm package using code from this repository. In my possession is the "minified" js file called http_www.webglearth.com_v2_api.js, which is automatically downloaded by IntelliJ when the <script src=""> tag ...

Looking to extract an Instagram post caption using Java Selenium?

My code is able to print hashtags from a post, but it doesn't seem to be printing the caption. The error message indicates that the caption should be treated as an element. driver.findElement(By.xpath("//*[@id=\"react-root\"]/section/main/a ...

Automatically populate fields with pre-filled information

In my database, I have a table named "Produits": public function up() { Schema::create('produits', function (Blueprint $table) { $table->id(); $table->string('reference')->nullable(); ...

Discover and eliminate nested levels

How can I locate and delete a specific value with the ID "5cc6d9737760963ea07de411"? Data: [ { "products" : [ { "id" : "5cc6d9737760963ea07de411", "quantity" : 1, "totalPrice" : 100, ...

Having difficulties in Vue while attempting to access a particular row

I encountered an error message stating Uncaught TypeError: snapShotChnaged.forEach is not a function. My goal is to retrieve specific row data, which is why I am utilizing the doc method. retrieveSpecificDonation() { firestore .collection('d ...

ng-include not functioning properly within ng-table

In the table, there is a data structure <tr ng-repeat="question in $data" ng-include="'/views/partials/questionList.html'"></tr> Within the questionList.html file: <td class="top-td" data-title="'ID'" sortable="&ap ...