Javascript: negative lookbehind equivalent?
Is there a way to achieve the equivalent of a negative lookbehind in javascript regular expressions? I need to match a string that does not start with a specific set of characters.
It seems I am unable to find a regex that does this without failing if the matched part is found at the beginning of the string. Negative lookbehinds seem to be the only answer, but javascript doesn't have one.
EDIT: This is the regex that I would like to work, but it doesn't:
(?<!([abcdefg]))m
So it would match the 'm' in 'jim' or 'm', but not 'jam'
Lookbehind Assertions got accepted into the ECMAScript specification in 2018. This has been implemented in V8 and shipped without flags with Google Chrome v62 and in Node.js v6 behind a flag and v9 without a flag. So, if you're developing for a Chrome-only environment (such as Electron), or Node, you can start using lookbehinds today!
Positive lookbehind usage:
console.log(
"$9.99 €8.47".match(/(?<=$)d+(.d*)?/) // Matches "9.99"
);
As Javascript supports negative lookahead, one safe way to do it is:
Let say you want to do a lookbehind like this
(?<!([abcdefg]))m
Apply your pattern "reversed" using a lookahead (be careful of the reversed matching expression inside the lookahead, in this case, it stays the same)
m(?!([abcdefg]))
reverse all the matched tokens
Examples:
I define the following functions:
const reverse = s => s.split('').reverse().join('');
const test = (stringToTests, reversedRegexp) => stringToTests
.map(reverse)
.forEach((s,i) => {
const match = reversedRegexp.test(s);
console.log(
stringToTests[i],
match,
'token:',
match ? reverse(reversedRegexp.exec(s)[0]) : 'Ø'
);
});
Example 1:
Following @andrew-ensley's question:
test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/)
Outputs:
jim true token: m
m true token: m
jam false token: Ø
Example 2:
Following @neaumusic comment (match max-height
but not line-height
, the token being height
):
test(['max-height', 'line-height'], /thgieh(?!(-enil))/)
Outputs:
max-height true token: height
line-height false token: Ø
Mijoja's strategy works for your specific case but not in general:
js>newString = "Fall ball bill balll llama".replace(/(ba)?ll/g,
function($0,$1){ return $1?$0:"[match]";});
Fa[match] ball bi[match] balll [match]ama
Here's an example where the goal is to match a double-l but not if it is preceded by "ba". Note the word "balll" -- true lookbehind should have suppressed the first 2 l's but matched the 2nd pair. But by matching the first 2 l's and then ignoring that match as a false positive, the regexp engine proceeds from the end of that match, and ignores any characters within the false positive.
链接地址: http://www.djcxy.com/p/74828.html上一篇: 如何匹配但不捕获正则表达式的一部分?