Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to (?!y) but before a word

Why can't I use (?!y)apple, if i want to exclude "yapple"?

What is alternative to (?!y) before a word?

http://jsfiddle.net/ksevelyar/SbCCx/4/

like image 952
ksevelyar Avatar asked Jan 19 '23 05:01

ksevelyar


2 Answers

To answer your original question:

You can explecitely encode "preceeded by either nothing (beggining of string) or a non-y character"

/(?:^|[^y])apple/

or depending on what you want to do, you can use a word-boundary match

/\bapple/

\b matches the boundary between an alphanumeric character (\w) and a non-alphanumeric character (\W)


Other environments (like Perl) sometimes have this look-behind functionality conveniently builtin:

/(?=)/   positive lookahead
/(?!)/   negative lookahead
/(?<=)/  positive lookbehind
/(?<!)/  negative lookbehind

As for the problem of not replacing things inside a pre

Perhaps it would be easier if you did a two step process: first remove all the text inside <pre> tags from your string, then do the replacements and then add the hidden text back after you are done.

like image 160
hugomg Avatar answered Jan 21 '23 18:01

hugomg


(?!...) is a lookahead, which will look beyond the end of your regex to find (or not find, in this case because its a negative-lookahead) characters...

You probably wanted to write a lookbehind, or (?<!...). Something like /(?<!y)apple/, however they aren't supported by the javascript regular expression engine.

but see missingno's answer for alternatives, but its difficult to suggest one over the other without better understanding what exactly you are trying to do.

like image 31
J. Holmes Avatar answered Jan 21 '23 17:01

J. Holmes