Regular expressions help eliminate extra spaces and any spaces that occur before characters

I am currently working on creating a regular expression to ensure there are no double spaces in a string, while also requiring a single space before the characters MO or GO, with no spaces allowed at the start or end of the string.

Example 1: It is 40 GO is correct

Example 2: It is 40GO is incorrect

Example 3: It is 40 GO is incorrect

So far, I have this regular expression: ^[^ ][a-zA-Z0-9 ,()]*[^;'][^ ]$, which successfully prevents spaces at the beginning and end of the string, as well as the ";" character. It's working well.

However, my challenge lies in disallowing double spaces anywhere in the string, and ensuring a space before instances of MO or GO.

After extensive research, I have tried these modifications:

To prevent double spaces:

^[^ ][a-zA-Z0-9 ,()]*((?!.* {2}).+)[^;'][^ ]$

To require a space before MO:

^[^ ][a-zA-Z0-9 ,()]*(?=\sMO)*[^;'][^ ]$

Unfortunately, neither of these changes seem to be working correctly. Any assistance in solving this issue would be greatly appreciated.

Answer №1

The lookahead (?!.* {2} can be excluded, and instead begin the match with a non-space character and end it with another non-space character, using a single space in an optionally repeated group.

If the string cannot have a ' or ;, then by utilizing [^;'][^ ]$, we ensure that the second last character is not one of those characters.

However, you can skip this part, as the character class [a-zA-Z0-9,()] does not include ; or '.

Keep in mind that when using a character class like [^ ] and [^;'], they expect only a single character, thus affecting the minimum length of the pattern you attempted.

Instead, you can eliminate the presence of GO or MO preceded by a non-space character.

^(?!.*\S[MG]O\b)[a-zA-Z0-9,()]+(?: [a-zA-Z0-9,()]+)*$

The pattern matches:

  • ^ Start of the string
  • (?!.*\S[MG]O\b) Negative lookahead ensuring that there is no non-whitespace character followed by either MO or GO. The word boundary \b prevents a partial word match
  • [a-zA-Z0-9,()]+ Beginning the match with 1 or more occurrences of any listed characters (without spaces)
  • (?: [a-zA-Z0-9,()]+)* Optionally repeating the same character class with a leading space
  • $ End of the string

Check out the Regex demo here

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 NEXT.JS application has encountered an error while exporting due to issues with the following path: /blogs/:post

I attempted to run next export : An error occurred while prerendering the page "/blogs/[post]". For more information, please visit: . The error message states that pages using getServerSideProps cannot be exported. Additional details can be fou ...

Clear the div content when submitting the form

I have a search bar for ISBN numbers and a submit button. When the form is submitted, the results are displayed in a div below the form, which works fine. However, my problem arises when I can repeatedly press submit and multiple divs appear one after ano ...

Runs tasks asynchronously in a sequential manner

I am attempting to run two functions asynchronously in series using node.JS, but I am struggling with the implementation. Currently, my code looks like this: Function 1: function search(client_id, callback) { clientRedis.keys('director:*', ...

Error in Angular $injector: Unknown provider

I'm encountering an issue while attempting to implement modals in angular $modalProvider <- $modal <- User.Ctlr Below is my app.js file 'use-strict'; var App = angular.module('App', ['ui.bootstrap']); And here ...

The utilization of React context is unsuccessful

Utilizing react context to pass the username across different components has been a challenge for me. I have structured my project into 3 main pages: - app.js - signIn (where the username is updated) - page1 (where I intend to display the updated username) ...

Pressing the 'GO' button will submit the form

After developing a hybrid app using Angular and Ionic, I encountered an issue where pressing the GO button or the arrow button on Android would submit the form even if it was not valid yet. Despite attempts to prevent this by detecting keypress events and ...

Incorporate Vuetify's v-stepper seamlessly with Vue router for dynamic functionality

Seeking assistance in integrating vuetify's v-stepper with vue router. Specific requirements include: Assigning each step its own route (e.g. /myform/step1, /myform/step2, /myform/step3, etc) Creating components for each step that are dynamically lo ...

When sending properties from one component to another in ReactJS, a null value is obtained

I am new to React and I'm struggling with passing props from one component to another. Below is my code, where I attempted to use this.props.value but it always returns "undefined" in the console. Oddly enough, when all HTML elements are placed in a s ...

"Incorporating JSON and Ajax to dynamically populate one select based on the selection in another select

I need to display data from a JSON file in select options, and here is the structure of my JSON file: [{ "vehicle": "car1", "type": [ {"name" : "BMW", "details" : [{ "color" : "red", "price" : "50000" }, ...

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

Importing Angular libraries with the * symbol

One of the key modules in my library is sha256. To import it, I had to use the following syntax: import sha256 from 'sha256'; However, while researching this issue, I came across a question on Stack Overflow titled: Errors when using MomentJS ...

Issues with Jquery Ajax POST request not resolving

Can you explain why the success code is not being executed in this request? $(document).ready(function(){ var post_data = []; $('.trade_window').load('signals.php?action=init'); setInterval(function(){ ...

Sparse planeBufferGeometry in THREE.js is a specialized type of geometry that

I am currently working with a file that contains sparse elevation data derived from GPS information. I have been utilizing this data to fill a PlaneBuffer array with elevations. var vertices = new Float32Array( (grid.NCOL*grid.NROW) * 4 ); for (var i = 0, ...

Issue with server side validation not triggering when JavaScript is turned off

I am facing an issue with validating an ASP.NET BasicDatePicker Control on the server side when JavaScript is disabled. The event does not seem to trigger as expected. Despite having JS Validation in place using .NET Validators, we are still seeing search ...

Increase initial zoom for React Three Fiber OrbitControls to provide a wider view

I've been working on a project in React Three Fiber using this codesandbox for practice. My query regarding the demo is about setting a wider initial zoom in OrbitControls to view more small stars. Can anyone help with this? Below is the code snippe ...

The pagination feature in Algolia instantsearch fails to display the results from the second page

While working with Laravel Vue and Algolia, I encountered an issue with pagination. The pagination seems to be functioning, but only the first page result is displayed. Clicking on pages 2, 3, etc. does not fetch the next page's results. Below are the ...

Using Umbraco Razor to transfer an array to JavaScript

In my Razor code, I am using a foreach loop to display images from the Multiple Media Picker in Umbraco. The Response.Write is just there for debugging purposes and the images are displaying correctly. My actual question pertains to populating the image ta ...

Does an empty object disrupt type passing in a generic array?

Looking to develop a versatile function that can pick a random element from an array while maintaining type information using Typescript 2.6.2. function sample<T>(array: T[]) : T { const index = Math.floor(Math.random() * array.length); return a ...

Exploring the world of design patterns using three.js and webpack

Looking to improve the organization of my code with three.js and webpack rather than having everything in a single file (like camera, meshes, lights, postprocessing, etc). I had the idea of using "manager modules" such as a LightManager class or a PostPro ...

Using JQuery to toggle the activation and deactivation of a click event

There are various HTML elements included below: <p class="accordion-header open" id="platform_0" onclick="validateScreens(this)">Platform 0</p> <p class="accordion-header open" id="platform_1" onclick="validateScreens(this)">Platform 0&l ...