简体   繁体   English

正则表达式匹配除给定完整单词之外的所有内容

[英]Regex that matches everything except given full word

This is similar to javascript regular expression to not match a word , but the accepted answer shows a regex that doesn't match if the word is inside the line.这类似于javascript 正则表达式 to not match a word ,但接受的答案显示了一个正则表达式,如果该词在行内,则该正则表达式不匹配。 I want to match everything except the full word.我想匹配除完整单词之外的所有内容。 It will match "__lambda__" .它将匹配"__lambda__"

This is also similar to my question Regex that match everything except the list of strings but that one gives a solution with String::split and I want to use normal match full string.这也类似于我的问题Regex 匹配除字符串列表之外的所有内容,但该问题给出了String::split的解决方案,我想使用普通匹配完整字符串。

For example, it should match everything except /^lambda$/ I would prefer to have a regex for this, since it will fit my pattern patching function.例如,它应该匹配除/^lambda$/之外的所有内容,我更喜欢为此使用正则表达式,因为它适合我的模式修补功能。 It should match lambda_ or _lambda and everything else - except full "lambda" token.它应该匹配 lambda_ 或 _lambda 以及其他所有内容 -除了完整的“lambda”标记。

I've tried this:我试过这个:

/^(.(?!lambda))+$/

and

/^((?!lambda).)+$/

this works这有效

/^(.*(?<!lambda))$/

but I would prefer to not have to use a negative lookbehind if I can avoid it (because of browser support).但如果我可以避免它(因为浏览器支持),我宁愿不必使用负面回顾。 Also, I have interpreter written in JavaScript that I need this for and I would like to use this in guest language (I will not be able to compile the regex with babel).另外,我有用 JavaScript 编写的解释器,我需要它,我想在来宾语言中使用它(我将无法用 babel 编译正则表达式)。

Is something like this possible with regex without lookbehind?在没有后视的情况下,使用正则表达式可以实现这样的事情吗?

EDIT:编辑:

THIS IS NOT DUPLICATE: I don't want to test if something contains or doesn't contain the word, but if something is not exact word.这不是重复的:我不想测试某些内容是否包含或不包含该单词,但是如果某些内容不是确切的单词。 There are not question on Stack Overflow like that. Stack Overflow 上没有这样的问题。

Question Regex: Match word not containing has almost as correct an answer as mine, but it's not the full answer to the question.问题正则表达式:匹配单词不包含的答案几乎和我的一样正确,但这不是问题的完整答案。 (It would help in finding solution, though.) (不过,这将有助于找到解决方案。)

I was able to find the solution based on How to negate specific word in regex?我能够找到基于如何否定正则表达式中的特定单词的解决方案

 var re = /^(?!.*\\blambda\\b).*$/; var words = ['lambda', '_lambda', 'lambda_', '_lambda_', 'anything']; words.forEach(word => { console.log({word, match: word.match(re)}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM