Is it possible to write a regex to find multiple spaces that are NOT within pairs of speech or quotation marks?

Regular expressions (regex) are a powerful tool for pattern matching and text manipulation. They allow us to search for specific patterns within a string and perform various operations based on the matches found. In TypeScript, regex can be particularly useful for tasks such as data validation, text parsing, and pattern extraction.



One common requirement is to find multiple spaces within a string, but only if they are not within pairs of speech or quotation marks. This can be a bit tricky to achieve with a single regex pattern, but it is definitely possible. Let's explore a couple of solutions to this problem.

Solution 1: Using Negative Lookahead and Lookbehind

One way to accomplish this is by using negative lookahead and lookbehind assertions. These assertions allow us to specify patterns that should not be present before or after a specific position in the string.



Here's a regex pattern that uses negative lookahead and lookbehind to find multiple spaces that are not within pairs of speech or quotation marks:

const regex = /(?
Let's break down the pattern: (? - Negative lookbehind assertion that ensures the space is not preceded by a single quote or double quote. s+ - Matches one or more whitespace characters. (?!['"]) - Negative lookahead assertion that ensures the space is not followed by a single quote or double quote. g - Global flag to find all matches within the string. To use this pattern, you can use the <code>exec</code> method of the regex object in a loop to find all matches within a string. Here's an example: const input = 'This is a "sample string" with multiple spaces.'; let match; while ((match = regex.exec(input)) !== null) { console.log(`Found match: ${match[0]}`); } The above code will output: Found match: Found match: Solution 2: Using a Combination of Regex and String Manipulation Another approach to solve this problem is by using a combination of regex and string manipulation functions. This approach involves finding all occurrences of speech or quotation marks and replacing the spaces within those occurrences with a placeholder character. Then, we can use a simple regex pattern to find the remaining spaces. Here's an example implementation: const input = 'This is a "sample string" with multiple spaces.'; const placeholder = '@@SPACE@@'; // Replace spaces within speech or quotation marks with a placeholder const replaced = input.replace(/(['"])(.*?)1/g, (match, p1, p2) => { return p2.replace(/s/g, placeholder); }); // Find remaining spaces const regex = /s+/g; let match; while ((match = regex.exec(replaced)) !== null) { const spaces = match[0].replace(new RegExp(placeholder, 'g'), ' '); console.log(`Found match: ${spaces}`); } The above code will output the same result as the previous solution: Found match: Found match: These are two possible solutions to find multiple spaces that are not within pairs of speech or quotation marks using regex in TypeScript. Depending on your specific use case, you can choose the solution that best fits your requirements. I hope you found this article helpful. Happy coding! Share this:FacebookX Related Posts: Check Whether a String Matches a Regex in Js Regular expressions, or regex, are powerful tools for pattern matching in JavaScript. They allow you to search, validate, and manipulate... regex not returning results of a search (problem with white space) Regex Not Returning Results of a Search: Problem with White Space Regular expressions (regex) are powerful tools for searching and... Regex for Password Must Contain at Least Eight Characters, at Least One Number and Both Lower and Uppercase Letters and Special Characters When it comes to creating a secure password, it’s important to have certain requirements in place to ensure the strength... How to display diacricts marks correctly – using Webpack, Typescript How to Display Diacritic Marks Correctly – Using Webpack and TypeScript When working with diacritic marks, such as accents or...
Posted September 17, 2023 in React by J. Kolby Tags: React Comments Leave a Reply Cancel replyYour email address will not be published. Required fields are marked *Comment * Name * Email * Website Save my name, email, and website in this browser for the next time I comment.
JS Duck Privacy Policy © Copyright 2023
window.WPCOM_sharing_counts = {"https:\/\/js-duck.com\/is-it-possible-to-write-a-regex-to-find-multiple-spaces-that-are-not-within-pairs-of-speech-or-quotation-marks\/":2988}; var ce4wp_form_submit_data = {"siteUrl":"https:\/\/js-duck.com","url":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","nonce":"eaf3f26209","listNonce":"d516e983a4","activatedNonce":"5241230576"}; ( function() { var skipLinkTarget = document.querySelector( 'main' ), sibling, skipLinkTargetID, skipLink; // Early exit if a skip-link target can't be located. if ( ! skipLinkTarget ) { return; } /* * Get the site wrapper. * The skip-link will be injected in the beginning of it. */ sibling = document.querySelector( '.wp-site-blocks' ); // Early exit if the root element was not found. if ( ! sibling ) { return; } // Get the skip-link target's ID, and generate one if it doesn't exist. skipLinkTargetID = skipLinkTarget.id; if ( ! skipLinkTargetID ) { skipLinkTargetID = 'wp--skip-link--target'; skipLinkTarget.id = skipLinkTargetID; } // Create the skip link. skipLink = document.createElement( 'a' ); skipLink.classList.add( 'skip-link', 'screen-reader-text' ); skipLink.href = '#' + skipLinkTargetID; skipLink.innerHTML = 'Skip to content'; // Inject the skip link. sibling.parentElement.insertBefore( skipLink, sibling ); }() ); var hcbVars = {"showCopyBtn":"1","copyBtnLabel":"Copy code to clipboard"}; _stq = window._stq || []; _stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"223076394\",\"post\":\"2988\",\"tz\":\"0\",\"srv\":\"js-duck.com\",\"j\":\"1:14.5\"}") ]); _stq.push([ "clickTrackerInit", "223076394", "2988" ]); wp.i18n.setLocaleData( { 'text direction\u0004ltr': [ 'ltr' ] } ); var _wpUtilSettings = {"ajax":{"url":"\/wp-admin\/admin-ajax.php"}}; var dracula = {"homeUrl":"https:\/\/js-duck.com","ajaxUrl":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","pluginUrl":"https:\/\/js-duck.com\/wp-content\/plugins\/dracula-dark-mode","settings":{"excludes":[""],"colorMode":"presets","preset":"dracula"},"isPro":"","upgradeUrl":"https:\/\/js-duck.com\/wp-admin\/admin.php?billing_cycle=annual&page=dracula-pricing","nonce":"e51f58d582"}; var sharing_js_options = {"lang":"en","counts":"1","is_stats_active":"1"}; var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-facebook' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-facebook' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomfacebook', 'menubar=1,resizable=1,width=600,height=400' ); return false; } } ); } )(); var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-x' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-x' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomx', 'menubar=1,resizable=1,width=600,height=350' ); return false; } } ); } )();