简体   繁体   English

正则表达式:如果在 x 范围内以 char 开头,则不匹配

[英]Regex: dont match if preceeded by char in range x

I am trying to use Regex (c#) to do the following:我正在尝试使用 Regex (c#) 执行以下操作:

  • Only match if search string '70' is not preceded by ID=" (case insensitive)仅当搜索字符串'70'前面没有ID="时才匹配(不区分大小写)
  • And only match if string before search string '70' does not contain '+'并且仅当搜索字符串'70'之前的字符串不包含'+'时才匹配

Example Text (linebreaks only for visuals):示例文本(仅用于视觉效果的换行符):

ID="70" Testtext
MultilingualText Uid="70"
Test="+#12-A170"
CV_70

i got the first condition via我得到了第一个条件

(?i)(?<!ID=\")70

which will only match 70 in line 3 & 4 but i have no idea how to exclude the line containing the '+' .这将只匹配第 3 行和第 4 行中的70 ,但我不知道如何排除包含'+'的行。 The position of '+' is variable in front of the search string. '+'的 position 在搜索字符串前面是可变的。

You might use你可能会使用

(?i)(?<!\+.*)(?<!ID=")70

The pattern matches模式匹配

  • (?i) Modifier for case insensitive (?i)不区分大小写的修饰符
  • (?<.\+.*) If a + is not on the left (?<.\+.*)如果+不在左边
  • (?<!ID=") If ID+ is not directly to the left of the current position (?<!ID=")如果ID+不是直接在当前 position 的左边
  • 70 Match 70 70匹配 70

.NET Regex demo .NET 正则表达式演示

string pattern = @"(?i)(?<!\+.*)(?<!ID="")70";
string input = @"ID=""70"" Testtext
    MultilingualText Uid=""70""
    Test=""+#12-A170""
    CV_70";

foreach (Match m in Regex.Matches(input, pattern))
{
    Console.WriteLine(m.Value);
}

Output Output

70

Update更新

The final working pattern as commented by @ anubhava matching any char except double quotes @anubhava评论的最终工作模式匹配除双引号外的任何字符

(?i)(?<!\+[^"]*)(?<!ID=")70

.NET regex demo .NET 正则表达式演示

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

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