简体   繁体   English

排除正则表达式中的字符串

[英]Excluding a string in a regular expression

For example, I have some expression like that 例如,我有一些这样的表达方式

expression1
expression2 expression3

I want to match "expression2 expression3" in a regular expression if "expression1" is not an unwanted string (Let me call it unwanted.). 如果“expression1”不是一个不需要的字符串(我称之为不需要的字符串),我想在正则表达式中匹配“expression2 expression3”。 So, it should be like that: 所以,它应该是这样的:

unwanted
expression2 expression3 // Not Matched...

string
expression2 expression3 // Matched...

How can I do this? 我怎样才能做到这一点? I have tried something like that: 我尝试过类似的东西:

(?!unwanted\n)(expression2)[ ]+(expression3)

But it doesn't work. 但它不起作用。 What can be the problem? 可能是什么问题?

Thanks in advance... 提前致谢...

Capture the unwanted string into Group 1 and check if it is undefined . 将不需要的字符串捕获到组1中,并检查它是否未定义 If it is, there is no unwanted text and you may grab that match, else, discard it: 如果是,则没有不需要的文本,您可以获取该匹配,否则,丢弃它:

 var regex = /(unwanted\\n)?(expression\\d+)\\s+(expression\\d+)/g; var str = "unwanted\\nexpression2 expression3\\n\\nstring\\nexpression4 expression5"; var res = [], m; while ((m = regex.exec(str)) !== null) { if (m[1] === undefined) res.push(m[0]); } console.log(res); 

Maybe you could work on from this: 也许你可以从这个工作:

(?!unwanted.*)(?:^.{1,8}).*\s*(expression2 expression3)

Basically it makes sure the expressions are preceded by at least the number of characters in unwanted , that isn't unwanted . 基本上它确保表达式前面至少有unwanted的字符数,这 unwanted

If you only want the expressions you'll get them in capture group 1. 如果您只想要表达式 ,则可以在捕获组1中获取它们。

See it here at regex101 . 在regex101上查看

Edit: Looking at this one's I realize it's probably full of caveats, but it might get you started. 编辑:看看这个,我意识到它可能充满警告,但它可能会让你开始。 (can't see them now though ;) (虽然现在看不到;)

Edit 2: Alternative (better I believe) requiring something , but not allowing unwanted anywhere, on the line before: 编辑2:替代(好,我相信),需要的东西 ,但在此之前不允许任何地方不需要的 ,就行了:

^(?!.*unwanted.*).+[\r\n](expression2 expression3)

Here it is at regex101 . 这是regex101

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

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