比较c中包含随机URL的两个字符串
本文关键字:两个 字符串 包含随 URL 比较 | 更新日期: 2023-09-27 18:27:57
我需要比较以下字符串。我遇到的问题是两个字符串中的url每次都会不同,例如:
www.google.com
http://www.google.com
谷歌网站!
由于URL不匹配,所以contains无法与字符串匹配。
String1 = "This is my string http://www.google.co.uk and that was my url"
String2 = "this is my string google.gr and that was my url"
所以我基本上想比较字符串的内容减去URl,每个字符串每次都可以包含不同的文本,所以每次在同一位置查找URl是行不通的。
我在这里广泛搜索了这个问题的答案,但我找不到一个有效的解决方案。
提前感谢
使用正则表达式删除链接:
String string1 = "This is my string http://www.google.co.uk and that was my url";
String string2 = "this is my string http://google.gr and that was";
Regex rxp = new Regex(@"http://[^'s]*");
String clean1 = rxp.Replace(string1, "");
String clean2 = rxp.Replace(string2, "");
现在您可以比较clean1和clean2。上面的OFC regexp只是一个例子,它只会删除以"http://"开头的url。你可能需要一些更复杂的东西,基于你的真实数据。
使用正则表达式:
Regex regex = new Regex(@"'s((?:'S+)'.(?:'S+))");
string string1 = "This is my string http://www.google.co.uk and that was my url.";
string string2 = "this is my string google.gr and that was my url.";
var string1WithoutURI = regex.Replace(string1, ""); // Output: "This is my string and that was my url."
var string2WithoutURI = regex.Replace(string2, ""); // Output: "this is my string and that was my url."
// Regex.Replace(string1, @"'s((?:'S+)'.(?:'S+))", ""); // This can be used too to avoid having to declare the regex.
if (string1WithoutURI == string2WithoutURI)
{
// Do what you want with the two strings
}
解释正则表达式's((?:'S+)'.(?:'S+))
1。's
将匹配任何空白字符
2.((?:'S+)'.(?:'S+))
将匹配url,直到下一个空白字符
2.1.(?:'S+)
将匹配任何非空白字符,而不会再次捕获组(使用?:)
2.2.'.
将匹配字符".",因为它将始终存在于url 中
2.3.(?:'S+))
再次匹配任何非空白字符,而无需再次捕获组(使用?:)以获取点之后的所有内容。
这应该会奏效。。。