如何在C#中出现特定字符串之前获取字符串的第一部分

时间:2019-09-18 12:32:00

标签: c#

我有一个字符串-

<span style=\"font-weight: 800\">Residence, Effective Date: NA</span> <br />6367 US HIGHWAY 70 EAST<br />LA GRANGE NC 28551 <br />

我想在第一次出现<br />之前获取字符串的第一部分,并且所选部分应类似于-

<span style=\"font-weight: 800\">Residence, Effective Date: NA</span>

目前我在做-

string dictVal = "<span style=\"font-weight: 800\">Residence, Effective Date: NA</span> <br />6367 US HIGHWAY 70 EAST<br />LA GRANGE NC 28551 <br />";

                string[] items = dictVal.Split(new char[] { '<' },
                         StringSplitOptions.RemoveEmptyEntries);
                string firstPart = string.Join("<", items.Take(3));

但是它不起作用。

2 个答案:

答案 0 :(得分:2)

只需使用string.Substringstring.IndexOf

string firstPart = dictVal.Substring(0, dictVal.IndexOf("<br />"))

答案 1 :(得分:0)

如果只想参加第一部分,可以通过以下方式使用Regex.Split

using System.Text.RegularExpressions;

string dictVal= "< span style =\"font-weight: 800\">Residence, Effective Date: NA</span> <br />6367 US HIGHWAY 70 EAST<br />LA GRANGE NC 28551 <br />";
string first_value = Regex.Split(mystring, "<br />")[0]; //The 0 gets the first portion of the array, in this case it is the desired value

// And if you want to remove any spaces at the beginning and at the end of the string
string trim = first_value.Trim();