Regular expressions (regex) can be utilized to identify patterns in text and can be configured to only match when the

I'm attempting to create a regular expression in Java or JavaScript that will match the specified regex pattern only when the total character count is less than 13 (with a minimum of 4 characters).

(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ DDD)?)   ← originally posted

(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ [A-Z]+)?)

The following values should (and do) match:

MED-123
COTA-1224
MED4
COTB-892K777
MED-33 DDD
MED-234J5678

This value matches, but I don't want it to (I want to only match if there are fewer than 12 characters total):

COT-1111J11111111111111

You can view the examples at

I've attempted to group my expression and use {4,12} at the end, but this just looks for 4 to 12 instances of the entire expression matching.

I have a feeling like I might be overlooking something simple... Thank you in advance for your assistance!

Answer №1

A clever solution is to utilize negative look-ahead in your regex pattern:

(?!.{13,})(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ DDD)?)

By ensuring that the match must start with either COT or MED and must have at least one digit following it, you are already guaranteeing a minimum of 4 characters in the match.

Answer №2

After attempting to group my expression and adding {4,12} at the end, I realized that it was only looking for 4 to 12 instances of the entire expression matching.

The reason why your regex is searching for 4 to 12 instances of the whole expression is because you forgot to include a word boundary \b. Your regex is correct, just remember to add the word boundary for the desired outcome. You can refer to this DEMO.

Your current regex appears complicated and somewhat difficult to interpret. It also seems restricted to specific characters such as JK, unless intentional. For a more versatile pattern, consider using the following:

(COT|MED)[AB]?-?[\dJK]{1,8}(\s+D{1,3})?\b

(COT|MED): matches either COT or MED

[AB]?: matches A or B optionally due to the presence of ?

-?: matches - if present

[\dJK]{1,8}: This matches a number, J, or K with a length ranging from one to eight characters.

(\s+D{1,3})?: matches a space followed by D between one to three times, and is optional

\b: crucial for establishing boundaries to prevent capturing excess patterns beyond what is intended

View the demonstration DEMO2

Answer №3

The solution you seek is

(?!\S{13})(?:COT|MED)[ABCD]?-?\d{1,4}(?:[JK]+\d*|(?: [A-Z]+)?)

View regex example

Keep in mind that determining the length of a phrase with internal spaces or not forming a complete string can be challenging due to unclear boundaries. Thus, (?!\S{13}) acts as a workaround by ensuring there are no 13 or more non-whitespace characters without any spaces in between.

Breakdown of the regular expression:

  • (?!\S{13}) - Validates if the succeeding substring does not contain exactly 13 non-whitespace characters
  • (?:COT|MED) - Matches either COT or MED
  • [ABCD]?-? - Optional occurrences of A, B, C, D, followed by an optional hyphen -
  • \d{1,4} - Represents digits ranging from 1 to 4
  • (?:[JK]+\d*|(?: [A-Z]+)?) - Two alternatives within a group:
    • [JK]+\d* - Indicates one or more occurrences of J or K followed by zero or more digits
    • (?: [A-Z]+)? - Allows for an optional space and at least one uppercase Latin letter

Answer №4

According to this response, one approach to resolving this issue is:

(?=(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ DDD)?))(?={4 , 12})

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

Extracting data from a JSON store in Ext JS 4.1.3: A step-by-step guide

In my Ext.data.Store, I have language variables stored in JSON format like this: { "language":"en_GB", "data":[ {"fieldName":"browserInfo","fieldValue":"Descriptive text"} ] } This is the store I've set up: Ext.local.langStore ...

What is the best way to check if a specific value is present in a JavaScript Array using a Function?

When a person uses an input field to type in a value, I have created the variable 'Ben' for that purpose. My goal is for a function to loop through the nameArray and return either true or false. Unfortunately, the script I've written isn& ...

Instructions on creating a Superfish menu with a vertical layout in the first level and a horizontal layout in the second level

Currently, I am using the Superfish menu in Drupal7 and have designed my first item level to be vertical. However, I now want to style my second item level horizontally. I have tried various CSS approaches and added some class names via jQuery like $(&apo ...

Adapting JavaScript functions from IE to work on Firefox and Chrome: A comprehensive guide

I have encountered an issue with a function that retrieves the selected text range within a contenteditable div. While it works perfectly fine in Internet Explorer, it doesn't seem to work in Firefox and Chrome. Could someone kindly provide guidance ...

Is it expected to conceal children who are 2 years old?

I came across the following HTML code snippet: <ul id="product_create-header" class="stepy-header"> <li id="product_create-head-0" class="stepy-active"> <div>Categoría</div><span>Categoría</span> </ ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Are websites built with HTML and JavaScript considered secure in today's digital age?

In the scenario where I create a website using HTML5, Javascript, and CSS3 with no forms or input fields other than mouse clicks on links, as well as no logins, messaging, or comments - will this site still be vulnerable to attacks? Recently, my hosting s ...

Guide on efficiently inserting multiple records into a MySQL database using Node.js and also implementing a check to insert only when the record does not already exist

I need to add numerous records to a table while also checking for duplicates to ensure that only new records are inserted. I have successfully inserted a single record by checking for duplicates using the code below. connection.query(` INSERT INTO pla ...

How can I safeguard my app from crashing when the initial state is set by undefined props?

What is the best way to prevent the state from crashing if props native_languages[0] does not exist? This is my attempt at protecting the app, but it still crashes when native_languages[0] does not exist: this.state = { language: props.currentDocu ...

Ways to precisely define a matrix of type Integer[][] in a coding scenario

It's an easy question for someone skilled in this. Create a two-dimensional array named 'res' with some hard-coded values like the following: Integer[][] res = new Integer[][] {.....hard code some values here on 2 dim...} How can you modif ...

What is the best way to add stripes to a button for a colorful touch

Can the button be styled with colors similar to those shown in the image? https://i.sstatic.net/3o1Jb.png ...

Maven's test execution is displaying an incorrect count of tests

While Maven successfully executes the test scripts, it is providing an incorrect test count. Let me explain the scenario: Currently, I have 18 test cases. When running them through Maven, 17 are skipped and this leads to the following output: Tests run: ...

The Ionic framework lacks support for the firebase and auth properties found in Firebase

Currently, I am developing a user-generated content feature along with buttons using ionic 5 and integrating it with the firebase app. I have been studying posts to incorporate them into my application. I am utilizing: "firebase": "^8.1.1&q ...

"Dependencies are missing in the pom file generated by 'gradle publish' command

Whenever I attempt to publish artifacts to my personal artifactory repository, I have noticed that the pom file being published does not contain the dependencies of the project. What could be causing this issue in my build? buildscript { repositories ...

Implement an event listener on the final element of a webpage utilizing querySelector

I need help with a password security check feature that changes field borders to green or red based on certain conditions. Despite successfully implementing it, the JavaScript code only selects the first field (nickname) instead of the last one. I've ...

`Is there a way to move a value between webpages by utilizing local storage?`

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>TechSavvy</title> </head> <body> <form action="apply.html" method="post"> <div class="consultantinformation" ...

How can require.js be effectively used in conjunction with web workers?

As of now, my current project involves the task of transitioning an existing web application to require.js. Most aspects of the process are proceeding smoothly, except for the functionality that utilizes web-workers. One such example is a worker defined in ...

Utilizing the Parent Global Variable within an iFrame's URL

I currently have the following code hosted on my domain at thedomain.com/myapp/index.php <?php ini_set('display_errors',1); error_reporting(E_ERROR); $storeId = 123; ?> <!DOCTYPE html> <html class="no-js" lang="en"> <head ...

"Provide information, then open a new webpage by clicking on a button. Perform various actions with the form by using type

Is there a way to quickly submit form entries to my database and then automatically redirect to a new page? My current situation requires that submitted information is stored in the DB before directing users to a thank you page, all in one seamless click! ...

Every array must consist of particular elements or names

How do I verify that an object containing arrays, passed as a parameter to my jQuery plugin, includes specific members/names? For instance, I need to confirm if the object below includes 'name', 'ID' & 'Location', all thr ...