有人可以帮我改进这部分代码吗?
字符串类似于:当前每小时价格 (HOEP):$20.09/MWh (2.01¢/kWh)。这是网站上的一行,其中 20.09 和 2.01 的数据随时间变化
static void get_HOEP(string web)
{
int x = web.IndexOf("Current Hourly Price");
...
}
我只想显示如下内容:当前每小时价格:2.01 ¢/kWh
感谢帮助
请您参考如下方法:
使用正则表达式,结果将在变量结果中。
var source="Current Hourly Price (HOEP): $20.09/MWh (2.01¢/kWh)";
var regex=new Regex(@"Current Hourly Price \(HOEP\): \$\d+\.\d\d/MWh \((\d+\.\d\d)¢/kWh\)");
var result=regex.Replace(source,"Current Hourly Price $1 ¢/kWh");
--编辑--全类版
public static class PriceParser {
private const string MATCH_STRING = @"Current Hourly Price \(HOEP\): \$\d+\.\d\d/MWh \((\d+\.\d\d)¢/kWh\)";
private const string REPLACE_STRING = @"Current Hourly Price $1 ¢/kWh";
private static readonly Regex regex=new Regex(MATCH_STRING,RegexOptions.Compiled);
private static readonly Regex entirePageRegex=new Regex(string.Format("^.*{0}.*$",MATCH_STRING),RegexOptions.Compiled|RegexOptions.Singleline);
public static void get_HEOP1(string web) {
Console.WriteLine(regex.Replace(web,REPLACE_STRING));
}
public static void get_HEOP2(string web) {
Console.WriteLine(entirePageRegex.Replace(web,REPLACE_STRING));
}
}
PriceParser.get_HEOP1(web) 简单地替换搜索字符串中的匹配项
PriceParser.get_HEOP2(web) 用替换字符串替换整个 web
