在字符串之后和字符串之前的值之前的值

时间:2013-10-31 10:58:52

标签: c# regex string parsing

我有一个这样的字符串:

  

Error=0,0<br>Federal withhold=1.00<br>FICA=0.00<br>Medicare=0.00<br>Federal Supplemental withhold=0.00<br>State withhold=361.32<br>State Supplemental withhold=0.00<br>City withhold=0.00<br>City Supplemental withhold=0.00<br>City Resident withhold=0.00<br>City Resident Supplemental withhold=0.00<br>County withhold=0.00<br>County Supplemental withhold=0.00<br>School withhold=0.00<br>School Supplemental withhold=0.00<br>SDI withhold=0.00<br>SDI employer withhold=0.00<br>SUI employer withhold=0.00<br>Version=2013.01,1.02<br>No messages

从这个字符串中我想提取实际为State withhold的{​​{1}}的值。

我在c#字符串中有这个字符串,我尝试使用361.32IndexOf但是我无法获得该值,直到该特定字后Substring <br>为止{ {1}}。

5 个答案:

答案 0 :(得分:5)

使用正则表达式State withhold=([^<]+)<并阅读Match().Captures[1]

中的值

http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx

答案 1 :(得分:1)

String s = "Error=0,0<br>Federal withhold=1.00<br>FICA=0.00<br>Medicare=0.00<br>Federal Supplemental withhold=0.00<br>State withhold=361.32<br>State Supplemental withhold=0.00<br>City withhold=0.00<br>City Supplemental withhold=0.00<br>City Resident withhold=0.00<br>City Resident Supplemental withhold=0.00<br>County withhold=0.00<br>County Supplemental withhold=0.00<br>School withhold=0.00<br>School Supplemental withhold=0.00<br>SDI withhold=0.00<br>SDI employer withhold=0.00<br>SUI employer withhold=0.00<br>Version=2013.01,1.02<br>No messages ";

var result = s.Split(new string[] { "<br>" }, StringSplitOptions.None).Where(x=>x.Split('=')[0]=="State withhold").Select(x=>x.Split('=')[1]);

答案 2 :(得分:1)

decimal value = decimal.Parse(
                input.Split("<br>")
                .Where(x => x.StartsWith("State withhold"))
                .First().Split('=').ToArray()[1]);

答案 3 :(得分:0)

您可以检查char是否为数字:char.IsDigit(c)

如果您拥有“州扣留”索引,您可以从那里开始:

string afterThis = "State withhold";
int i = myString.IndexOf(afterThis) + afterThis.Length;
string tmpString = String.Empty;
while(char.IsDigit(myString.charAt(i)) || char.Equals('.'))
{
    tmpString += myString.charAt(i); // save it to a temp string
    i++;
}
double value = double.Parse(tmpString);

答案 4 :(得分:0)

以下正则表达式应该有所帮助...

(?<=State\swithhold=).*?(?=\<br\>)