简体   繁体   English

使用正则表达式和C#识别另一个字符串中不存在的字符串

[英]Identify the string that does not exists in another string using regex and C#

I am trying to capture a string that does not contains in another string. 我正在尝试捕获另一个字符串中不包含的字符串。

string searchedString = " This is my search string";
string subsetofSearchedString = "This is my";

My output should be "Search string". 我的输出应该是“搜索字符串”。 I would like to go with only regex so that I can handle complex strings. 我只想使用正则表达式,以便处理复杂的字符串。

The below is the code that I have tried so far and I am not successful. 下面是到目前为止我尝试过的代码,但我没有成功。

 Match match = new Regex(subsetofSearchedString ).Match(searchedString );
 if (!string.IsNullOrWhiteSpace(match.Value))
 {
      UnmatchedString= UnmatchedString.Replace(match.Value, string.Empty);
 }

Update : The above code is not working for the below texts. 更新:上面的代码不适用于以下文本。

text1 = 'Property Damage (2015 ACURA)' Exposure Added Automatically for IP:Claimant DriverLoss Reserve Line :Property DamageReserve Amount $ : STATIP Role(s): Owner, DriverExposure Owner :Jaimee Watson_csr Author:
text2 = 'Property Damage (2015 ACURA)' Exposure Added Automatically for IP:Claimant DriverLoss Reserve Line :Property DamageReserve Amount $ : STATIP Role(s): Owner, Driver

Match match = new Regex(text2).Match(text1);

You can use Regex.Split : 您可以使用Regex.Split

var ans = Regex.Split(searchedString, subsetofSearchedString);

If you want the answer as a single string minus the subset, you can join it: 如果您希望答案是单个字符串减去子集,则可以将其加入:

var ansjoined = String.Join("", ans);

Replacing with String.Empty will also work: String.Empty替换也可以:

var ans = Regex.Replace(searchedString, subsetOfSearchedString, String.Empty);

Answer : 答:

Regex wasn't working for me because of the presence of metacharacters in my string. 正则表达式不适用于我,因为我的字符串中存在元字符。 Regex.Escape did not help me with the comparison. Regex.Escape没有帮助我进行比较。

String Contains worked like a charm here 字符串包含在这里就像一个魅力

if (text1.Contains(text2))
   {  
      status = TestResult.Pass;
      text1= text1.Replace(text2, string.Empty);
   }

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

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