Alternative (?! Y), but before the word

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

What is the alternative (?! Y) before the word?

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

+4
source share
3 answers

To answer your original question:

You can explecitely encode "have undergone nothing (beginning of line) or non-y character"

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

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

 /\bapple/ 

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


In other environments (for example, Perl), sometimes there are convenient functions for searching:

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

Regarding the issue of not replacing things inside pre

It might have been easier if you had done the two-step process: first remove all the text inside the <pre> tags from your line, then do the replacements and then add the hidden text after you are done.

+5
source

(?!...) is a lookahead that will look outside of your regular expression to find (or not find in this case because its negative-inverse characters) ...

You might want to write lookbehind, or (?<!...) . Something like /(?<!y)apple/ , however they are not supported by the javascript regex engine.

but see the lack of an answer to the alternatives, but it’s hard to offer one by one without understanding what exactly you are trying to do.

+3
source

JavaScript regexp is not the best ... Here is a (very) dirty workaround that might suit you:

 str = str.replace(/<pre>apple<\/pre>/g, "#DUMMY#"); str = str.replace(/apple/g, "sword"); str = str.replace(/#DUMMY#/g, "<pre>apple</pre>"); 

http://jsfiddle.net/pZ3c9/

Hope this helps you!

+1
source

Source: https://habr.com/ru/post/1382310/


All Articles