如何仅在最后一次出现特殊字符时拆分字符串,并在拆分后使用两边

0 c# regex string wpf split

我想在最后一次出现特殊字符时拆分字符串.

我尝试从浏览器解析选项卡的名称,所以我的初始字符串看起来像这样:

无标题 - 谷歌浏览器

由于存在Split功能,因此很容易解决.这是我的实现:

var pageparts= Regex.Split(inputWindow.ToString(), " - ");
InsertWindowName(pageparts[0].ToString(), pageparts[1].ToString());//method to save string into separate columns in DB
Run Code Online (Sandbox Code Playgroud)

这有效,但是当我得到这样的页面时会出现问题:

SQL注入 - 维基百科,免费的百科全书 - Mozilla Firefox

这里有两个破折号,这意味着,在分割完成后,数组中有3个单独的字符串,如果我将继续正常,数据库将包含第一列值"SQL注入"和第二列值"Wikipedia,免费百科全书".最后一个值将完全省略.

我想要的是数据库中的第一列将具有价值:SQL注入 - 维基百科,免费的百科全书"和第二列将具有:"Mozilla Firefox".这有可能吗?

我试图使用Split(" - ").Last()函数(甚至也是LastOrDefault()),但后来我只得到了一个最后一个字符串.我需要得到原始字符串的两面.刚刚划过最后一个破折号.

Hab*_*bib 8

你可以用String.SubstringString.LastIndexOf:

string str = "SQL injection - Wikipedia, the free encyclopedia - Mozilla Firefox";
int lastIndex = str.LastIndexOf('-');
if (lastIndex + 1 < str.Length)
{
    string firstPart = str.Substring(0, lastIndex);
    string secondPart = str.Substring(lastIndex + 1);
}
Run Code Online (Sandbox Code Playgroud)

创建一个扩展方法(或一个简单的方法)来执行该操作,并添加一些错误检查lastIndex.

编辑:

如果要拆分" - " (空间 - 空间),请使用以下计算lastIndex

string str = "FirstPart - Mozzila Firefox-somethingWithoutSpace";
string delimiter = " - ";
int lastIndex = str.LastIndexOf(delimiter);
if (lastIndex + delimiter.Length < str.Length)
{
    string firstPart = str.Substring(0, lastIndex);
    string secondPart = str.Substring(lastIndex + delimiter.Length);
}
Run Code Online (Sandbox Code Playgroud)

所以对于字符串:

"FirstPart - Mozzila Firefox-somethingWithoutSpace"
Run Code Online (Sandbox Code Playgroud)

输出将是:

FirstPart 
Mozzila Firefox-somethingWithoutSpace
Run Code Online (Sandbox Code Playgroud)