views:

34

answers:

2

I have a string:

users/554983490\/Another+Test+/Question????\/+dhjkfsdf/

How would i write a RegExp that would match all of the forward slashes NOT preceded by a back slash?

EDIT: Is there a way to do it without using a negative lookbehinds?

+2  A: 

You can use this :

/(?<!\\)\//

This is called a negative lookbehind.

I used / as the delimiters

(?<!   <-- Start of the negative lookbehind (means that it should be preceded by the following pattern)
  \\     <--  The \ character (escaped)
)      <-- End of the negative lookbehind
\/     <-- The / character (escaped)
Colin Hebert
+2  A: 

If your regular expressions support negative lookbehinds:

/(?<!\\)\//

Otherwise, you will need to match the character before the / as well:

/(^|[^\\])\//

This matches either the start of a string (^), or (|) anything other than a \ ([^\\]) as capture group #1 (). Then it matches the literal / after. Whatever character was before the / will be stored in the capture group $1 so you can put it back in if you are doing a replace....

Example (JavaScript):

'st/ri\\/ng'.replace(/(^|[^\\])\//, "$1\\/");
// returns "st\/ri\/ng"
gnarf
yes but this includes the letter before as well
Dick Savagewood
The negative lookbehind doesn't include it... The second match will, but if you don't support negative lookbehinds, its your only option... You could do something like `'st/ri\\/ng'.replace(/(^|[^\\])\//, "$1\\/");` in javascript for instance to add the backslash to any `/` that don't already have it.
gnarf