user1028880
user1028880

Reputation:

regex to match space but escaped space

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

regex to match space but escaped space I have tried:

Firstly to match escaped space(or any).

\\.

http://regex101.com/r/uL0mP8 works.

Next, to match space exclude the escaped space(or any).

(?!\\.)

http://regex101.com/r/fK3sW9 does not work.

What is wrong with the code? javascript.

Thanks

EDIT:

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

I should have used neggative 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??

OK lookbehinds are not supported in JavaScript. I'm not sure how http://regex101.com can output. perhaps PHP or others on serverside.

EDIT3:

This has been very tricky. See the full working code I post:

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

Upvotes: 1

Views: 1591

Answers (2)

Chris
Chris

Reputation: 8656

Are you trying to match all spaces excluding what you're calling an "escaped space".

You should be able to achieve that with a negative lookbehind:

(?<!\\)\s

Will match any space not preceded by \.

The second regex you were using (?!\\.)\s was using a negative lookahead, and searching for spaces not followed by \(any character), which is why it didn't work.

Edit: Lookbehinds won't work in javascript, learned something new.

Upvotes: 1

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

For the second case you can use: (?<!\\)

Edit: I don't usually work with javascript so i don't know of any quick shortcut, so i think you can do this at two steps:

  1. Perform a substitution (replace) using this regex: \\\s, replace with semicolon ; like this: var newCommand = command0.replace(/\\\s/g, ";");
  2. Then perform split using this regex: \s like this: var result = newCommand.split(/\s/);

Upvotes: 0

Related Questions