正则表达式匹配某些字符串并忽略它是否以某种模式开头

[英]Regex match certain string and ignore if it starts with some pattern


I have a following regular expression that I use in C# code that tries to match save some followed by some word and delete some followed by some word in a file.

我有一个以下正则表达式,我在C#代码中尝试匹配保存一些后跟一些单词并删除一些后跟文件中的一些单词。

\bsave\ssome\b\s[^\s]+|\bdelete\ssome\b\s[^\s]+

This works as expected. Now, I wanted to exclude those from the match that has a pattern like - save some and - delete some.

这按预期工作。现在,我想从具有类似模式的匹配中排除那些 - 保存一些 - 删除一些。

I tried using the following but it didn't work. In the expression below I just used the expression to ignore - save some Appreciate any help. (?!-\s\bsave\ssome\b\s[^\s])(\bsave\ssome\b\s[^\s]+|\bdelete\ssome\b\s[^\s]+)

我尝试使用以下但它没有用。在下面的表达式中,我只是使用表达式忽略 - 保存一些Appreciate任何帮助。 b \ S - (?!\ S \ BSAVE \ ssome \ B \ S [^ \ S])(\ BSAVE \ ssome \ [^ \ S] + | \ BDELETE \ ssome \ B \ S [^ \ S] + )

The demo is here

演示就在这里

1 个解决方案

#1


2  

You need to use a negative look-behind and group the pattern:

您需要使用负面的后视并对模式进行分组:

(?<!-\p{Zs}*)(?:\bsave\ssome\b\s[^\s]+|\bdelete\ssome\b\s[^\s]+)
^^^^^^^^^^^^  ^                                                ^  

See regex demo

请参阅正则表达式演示

The (?<!-\p{Zs}*) lookbehind fails a match if the save/delete some is preceded with - followed by zero or more spaces (use + if there must be at least one). I used \p{Zs} to only match horizontal whitespace. If you want to match newlines, use \s.

(?

A contracted regex version:

签约的正则表达式版本:

(?<!-\s*)\b(save|delete)\ssome\b\s\S+

Use the Explicit Capture flag with it. Since \ssome\b\s\S+ is common for both alternatives, you can move the end of the group to just include save and delete.

使用Explicit Capture标志。由于\ ssome \ b \ s \ S +对于两种备选方案都很常见,因此您可以将组的末尾移动到仅包括保存和删除。

C#:

var rx = @"(?<!-\s*)\b(save|delete)\ssome\b\s\S+";
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2016/01/14/54cf718d8ded2d87b15717819c99b629.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告