C# 使用regex和C标识另一个字符串中不存在的字符串#
我试图捕获另一个字符串中不包含的字符串C# 使用regex和C标识另一个字符串中不存在的字符串#,c#,regex,visual-studio-2015,C#,Regex,Visual Studio 2015,我试图捕获另一个字符串中不包含的字符串 string searchedString = " This is my search string"; string subsetofSearchedString = "This is my"; 我的输出应该是“搜索字符串”。我只想使用正则表达式,这样我就可以处理复杂的字符串 下面是我迄今为止尝试过的代码,我没有成功 Match match = new Regex(subsetofSearchedString ).Match(searchedStri
string searchedString = " This is my search string";
string subsetofSearchedString = "This is my";
我的输出应该是“搜索字符串”。我只想使用正则表达式,这样我就可以处理复杂的字符串
下面是我迄今为止尝试过的代码,我没有成功
Match match = new Regex(subsetofSearchedString ).Match(searchedString );
if (!string.IsNullOrWhiteSpace(match.Value))
{
UnmatchedString= UnmatchedString.Replace(match.Value, string.Empty);
}
更新:以上代码不适用于以下文本
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);
您可以使用
Regex.Split
:
var ans = Regex.Split(searchedString, subsetofSearchedString);
如果希望答案为单个字符串减去子集,则可以将其合并:
var ansjoined = String.Join("", ans);
替换为String.Empty也可以:
var ans = Regex.Replace(searchedString, subsetOfSearchedString, String.Empty);
答复:
正则表达式不适用于我,因为我的字符串中存在元字符。Regex.Escape并没有帮助我进行比较
这里的字符串很有魅力
if (text1.Contains(text2))
{
status = TestResult.Pass;
text1= text1.Replace(text2, string.Empty);
}
因此,您希望从所需的输出中获取字符串中与正则表达式模式不匹配的部分?当前代码如何不工作,您还希望第一个字母大写吗?输出不应该也包括searchedString
中的前导空格吗?@Sweeper我刚刚用不起作用的文本更新了我的问题。这回答了我原来的问题,因此接受了答案。