我有以下主字符串,其中包含链接名称和链接 URL。名称和 url 与 #;
结合。我想获取每个链接的字符串(名称和 url 即 My web#?http://www.google.com
),请参见下面的示例
string teststring = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
我想使用任何字符串函数获取三个不同的字符串:
- 我的网站#?http://www.google.com
- 我的 Web2#?http://www.bing.se
- 手册#?http://www.books.de
最佳答案
所以这看起来像是您想在 #;
之后的空格处拆分,而不是在 #;
本身处拆分。 C# 提供任意长度的lookbehinds,这使得这很容易。事实上,您应该先将 #;
替换为 #?
:
string teststring = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
teststring = Regex.Replace(teststring, @"#;", "#?");
string[] substrings = Regex.Split(teststring, @"(?<=#\?\S*)\s+");
就是这样:
foreach(var s in substrings)
Console.WriteLine(s);
Output:
My web#?http://www.google.com
My Web2#?http://www.bing.se
Handbooks#?http://www.books.se/
如果您担心您的输入可能已经包含您不想拆分的其他 #?
,您当然可以先进行拆分(使用 #;
在模式中),然后遍历 substrings
并在循环内执行替换调用。
关于c# - 从一个主字符串中获取不同的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13850334/