Here is a regex that works fine in most regex implementations:
(?<!filename)\.js$
This matches .js for a string which ends with .js except for filename.js
Javascript doesn't have regex lookbehind. Is anyone able put together an alternative regex which achieve the same result and works in javascript?
Here are some thoughts, but needs helper functions. I was hoping to achieve it just with a regex: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
Below is a positive lookbehind JavaScript alternative showing how to capture the last name of people with 'Michael' as their first name.
1) Given this text:
get an array of last names of people named Michael. The result should be:
["Jordan","Johnson","Green","Wood"]
2) Solution:
3) Check solution
Demo here: http://codepen.io/PiotrBerebecki/pen/GjwRoo
You can also try it out by running the snippet below.
EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.
In previous versions, you can do this:
This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.
Another edit:
It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:
works just as well:
Let's suppose you want to find all
int
not preceded byunsigned
:With support for negative look-behind:
Without support for negative look-behind:
Basically idea is to grab n preceding characters and exclude match with negative look-ahead, but also match the cases where there's no preceeding n characters. (where n is length of look-behind).
So the regex in question:
would translate to:
You might need to play with capturing groups to find exact spot of the string that interests you or you want't to replace specific part with something else.
This is an equivalent solution to Tim Pietzcker's answer (see also comments of same answer):
It means, match
*.js
except*filename.js
.To get to this solution, you can check which patterns the negative lookbehind excludes, and then exclude exactly these patterns with a negative lookahead.
If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.
^(?!filename).+\.js
works for metested against:
A proper explanation for this regex can be found at Regular expression to match string not containing a word?
Look ahead is available since version 1.5 of javascript and is supported by all major browsers
Updated to match filename2.js and 2filename.js but not filename.js
(^(?!filename\.js$).).+\.js