1

I need to find all slashes in a string excluding those with "<" symbol in front of it.

/(?!<)(\/)/g does not work like I want.

EDIT: I forgot to mention that I am using Javascript. The proposed solutions seem to be for php.

dtrinh
  • 163
  • 1
  • 11

3 Answers3

1

Visually, your mind was fooled.

This (?!<) looks like a negative lookbehind, but it's actually a negative
lookahead.

This (?<!<) is a negative lookbehind.

A note that putting an assertion first in a regex slows down the regex
10 to 30 times.

Put the lookbehind after the literal for better performance /(\/)(?<!<\/)/.


Addendum

If using JavaScript regex without support for lookbehind assertions,
you'd have to get a little creative. Depends on what you need to know
about the / character.
I'm assuming you need to know the location where it is found in the string.

Basically, the only reliable substitution for lookbehind assertions in JS
is to match the errant substring in order to advance the match position past it.
It's not a death sentence, you always know when you match a good forward slash.

Here is a JS sample how to do that

var target = '/</ //  asdf/  /><   <  / </';

var rx = /(?:<\/|(\/))/g;
var match;

while (match = rx.exec( target ) )
{
    if ( match[1] != null ) 
        console.log ( match[1] + " found at index " + match.index );
}
0
/(?<!<)([\/\\])/g

The \ is doing an 'escaped literal' as the slashes don't naturally dictate the character being captured.

You were doing a negative lookahead assertion. I changed that to a negative look-behind assertion.

This tool: https://regex101.com/ really helped me understand regex. It tells you what you are looking for.

Bryce Drew
  • 5,777
  • 1
  • 15
  • 27
0

You can use a negative lookbehind, i.e.:

/(?<!<\/)

Regex Explanation:

/(?<!<\/)

Match the character “/” literally «/»
Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!<\/)»
   Match the character “<” literally «<»
   Match the character “/” literally «\/»

Regex101 Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268