Regular expression to detect a space that is escaped

Given a string:

rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application\ Support/Sublime\ Text\ 3/Packages /Users/ken/Google\ Drive/__config-GD/ST3

Attempting to find a regex pattern that matches spaces, but excludes escaped spaces.

First attempt to match escaped space (or any character):

\\.

http://regex101.com/r/uL0mP8 successfully matches.

Next, trying to match spaces while excluding escaped spaces:

(?!\\.)

http://regex101.com/r/fK3sW9 does not produce the desired results.

What may be the issue with the code? It is written in javascript.

Thank you

EDIT:

(?<!\\) http://regex101.com/r/fZ5uP2 works!

I should have utilized Negative Lookbehind...

EDIT2:

var command0 = `rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application\ Support/Sublime\ Text\ 3/Packages /Users/ken/Google\ Drive/__config-GD/ST3`;

var regex = new RegExp('(?<!\\)\s')
var commandA = command0.split(regex);

Error -

Invalid regular expression: /(?<!\\)\s/: Invalid group

Oops, what is the workaround in JavaScript??

Okay, lookbehinds are not supported in JavaScript. I'm unsure how http://regex101.com can output. Perhaps for PHP or other server-side languages.

EDIT3:

This has been quite challenging. Check out the complete working code I have shared:

shell command to child_process.spawn(command, [args], [options]) node.js

Answer №1

Is your goal to match all spaces except for those you consider to be "escaped spaces"?

You can accomplish this by using a negative lookbehind:

(?<!\\)\s

This regex will match any space that is not preceded by a \.

The other regex pattern you tried, (?!\\.)\s, used a negative lookahead and was looking for spaces not followed by \(any character), which is why it did not yield the desired result.

Update: It turns out that lookbehinds do not function in JavaScript, which is a valuable lesson.

Answer №2

To tackle the second scenario, you may employ the following: (?<!\\)

Note: My expertise lies outside of javascript, hence, any convenient shortcuts are beyond my knowledge. However, I propose a two-step approach:

  1. Execute a substitution (replace) with the regex: \\\s, replacing it with a semicolon ; in this format:
    var newCommand = command0.replace(/\\\s/g, ";");
  2. Proceed to split using the regex: \s like so:
    var result = newCommand.split(/\s/);

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

Unable to locate phonepe.intentsdk.android.release:IntentSDK:2.4.1 while integrating React Native

android build gradle : // Configuration options for all sub-projects/modules are defined in the top-level build file. buildscript { ext { buildToolsVersion = "33.0.0" minSdkVersion = 21 compileSdkVersion = 33 targetSdkVersion = ...

Automatically submit upon selecting an option

Encountering some difficulties with the code provided below. Purpose of this code I have multiple list items (shown here is just a snippet) made up of select elements, options, and one submit input field. When an option is chosen, the user can click on ...

Adding text after a div in React-JS using Bootstrap: A quick guide

Just starting out with website development and I have a question. As I practice making this website, I am struggling to figure out how to add the text "To know more about us click here" below the 'Get started' button. I tried adding a simple < ...

Having trouble adding flexslider before a div element with jQuery

Hey there! I recently got flexslider from woothemes.com. The page structure I'm working with looks something like this: <div class="parentdiv anotherdiv"> <div class="child-div1">some buttons here</div> <div class="child-div2"& ...

Custom div element obstructs information window on map due to lack of auto panning feature

I created a unique div that is absolutely positioned on a Google Map. You can view the image below to see it. My issue is that the info window is being covered by this custom div element, as demonstrated in the picture. https://i.stack.imgur.com/1TgyQ.jpg ...

Reorder data in an array using a specific field in AngularJS

I am working with an array that looks like this: [Object,Object,Object]; Each object in the array has a property named "rate". I need to sort these objects based on their rate property. In my JavaScript, I have a variable called $scope.restaurants.data, ...

Dealing with nested try/catch mechanism in NodeJS

As a Node.js novice, I am delving into the realm of coding two nested try/catch blocks with retry logic. My goal is to have the inner try/catch block send any caught errors to the outer catch block, where I will increment a retry count by 1. Once this co ...

React-bootstrap-table Axios delete operation causing [object%20Object] to be displayed in the browser console

I am having trouble executing a delete operation using axios on a react-bootstrap-table, and encountering this error in the console DELETE http://localhost:9000/api/terminals/[object%20Object] Uncaught (in promise) Error: Request failed with status cod ...

Show a dynamic highchart graph displaying linear data retrieved from the database

I am attempting to present data retrieved from a database in a linear highchart format. Here is the JSON response from my database: [{"protocol":"tcp","date":"01/02/20","time":"00:10:20","total":281}, {"protocol":"udp","date":"01/02/20","time":"00:10:30", ...

The AngularJS templates' use of the ternary operator

Is there a way to implement a ternary operation in AngularJS templates? I am looking for a way to apply conditionals directly in HTML attributes such as classes and styles, without having to create a separate function in the controller. Any suggestions wo ...

Struggling with PHP variables and AJAX JavaScript

Hey everyone, I've made some edits and have a new question regarding a similar issue. On test.php in my Apache server, I have a PHP script that connects to a database and retrieves data from a table. <?php $con = mysqli_connect("localhost", "user" ...

Is there a way to design a catalog page for my website that doesn't include a shopping cart or detailed product pages?

I am looking to create a catalogue feature similar to Newegg's for my website, but with a simplified approach. I have never attempted something this advanced before and I am wondering if it is possible to achieve. My plan is to use PHP and JS for the ...

Can config values be dynamically set from an Excel file in Protractor?

I am currently working on parameterizing capabilities using an Excel sheet. For this task, I am utilizing the npm exceljs package for both reading and writing data. Below is a snippet of the code that demonstrates how I am trying to achieve this: //This f ...

Performing an HTTP GET request to an endpoint within a RESTful API

I am looking to integrate a feature in my web application that displays the list of online users on my website. To achieve this, I need to make an HTTP GET request to the URL which returns the user data in JSON format. The returned JSON data contains var ...

How can Firebase effectively manage multiple URLs for referencing?

I am facing a scenario with multiple users, each with a unique hashId assigned to them that differentiates their URLs. users/hashId/bla/blah The only variation in these URLs is the hashId value. While the client side updates data in firebase, I need to ...

Contrast and combine information from two JavaScript arrays of objects

I am struggling with comparing two arrays of objects based on a key. My goal is to compare the values, subtracting them when the keys match and displaying negative values for those not found in my target array. Additionally, I want to include all target o ...

Dynamic HTML DOM element name changes

One thing I'm considering is the process of dynamically changing element names in the DOM with JavaScript or jQuery when adding or removing child elements. For instance, if I decide to delete the second text box from a form that originally has three t ...

There is no result being returned by Model.findOne()

Why does Model.findOne() return null even when a valid collection is present in the respective Model? app.post("/fleetManagement", (req, res) => { const requestedDriverID = req.body.driverId; console.log(requestedDriver ...

Creating custom elements for the header bar in Ionic can easily be accomplished by adding your own unique design elements to the header bar or

I'm a beginner with Ionic and I'm looking to customize the items on the header bar. It appears that the header bar is created by the framework within the ion-nav-bar element. <ion-nav-bar class="bar-positive"> <ion-nav-back-button> ...

JavaScript forEach functionality is not compatible with Dynamics CRM 2016

I'm currently working on writing some JavaScript code for a ribbon button in Dynamics CRM 2016 that will extract phone numbers from a list of Leads displayed in the Active Leads window. However, I've encountered an error message when attempting ...