[英]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#代码中使用以下正则表达式尝试匹配,在文件中
save some
后跟一些单词,并delete some
后跟一些单词。
\\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
. 现在,我想从匹配中排除那些具有类似
- save some
- 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. 在下面的表达式中,我只是使用了表达式来忽略
- save some
感谢任何帮助。 (?!-\\s\\bsave\\ssome\\b\\s[^\\s])(\\bsave\\ssome\\b\\s[^\\s]+|\\bdelete\\ssome\\b\\s[^\\s]+)
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). 如果后面的
(?<!-\\p{Zs}*)
查找save/delete
失败,则匹配失败-
后面有零个或多个空格(如果必须至少有一个,则使用+
)。 I used \\p{Zs}
to only match horizontal whitespace. 我使用
\\p{Zs}
仅匹配水平空白。 If you want to match newlines, use \\s
. 如果要匹配换行符,请使用
\\s
。
A contracted regex version: 合同规定的正则表达式版本:
(?<!-\s*)\b(save|delete)\ssome\b\s\S+
Use the Explicit Capture
flag with it . 使用
Explicit Capture
标志用它 。 Since \\ssome\\b\\s\\S+
is common for both alternatives, you can move the end of the group to just include save
and delete
. 由于
\\ssome\\b\\s\\S+
在这两种选择中都是通用的,因此您可以将组的末尾移动到只包含save
和delete
。
C#: C#:
var rx = @"(?<!-\s*)\b(save|delete)\ssome\b\s\S+";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.