简体   繁体   English

使用正则表达式的两个预读字符串

[英]Two look-ahead strings using regex

I have a simple regex that looks like the following: 我有一个简单的正则表达式,如下所示:

var myRegex = /%(?!FOO%)([A-Za-z_]*)%/g; 

What I'm trying to do is find any instance of between two literal % quotes that isn't FOO . 我想做的是找到两个不是FOO %引号之间的实例。 So anything like BAR , WHATEVER etc would match. 因此,类似BARWHATEVER等的任何事物都将匹配。

My question is, what's the best way to extend this to look for multiple strings? 我的问题是,将其扩展为查找多个字符串的最佳方法是什么? Let's say I want to match anything that isn't FOO or BAR . 假设我想匹配所有非FOOBAR

var myRegex = /%(?!(FOO|BAR)%)([A-Za-z_]*)%/g; 

I tried the variant above, but that only seems to find the first match, FOO . 我尝试了上述变体,但似乎只能找到第一个匹配项FOO How do I make it find both? 如何找到两者?

You could try something like this : ( assuming this is what you wanna accomplish ) 您可以尝试执行以下操作:( 假设您要完成此操作

General way ( w/ lookbehind support ) 通用方式带后支持

(?<=%)(?!FOO|BAR)(\w+)(?=%)

JavaScript way ( w/o lookbehind support ) JavaScript方式 (无后支持

 var str = '%FOO%HELLO%BAR%WORLD%'; var match = str.match(/%(?!FOO|BAR)(\\w+)(?=%)/g).map(e => { return e.replace('%', ''); }); console.log(match); 

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

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