正则匹配的通用方法

来源:互联网 发布:直播人气软件 编辑:程序博客网 时间:2024/06/06 00:58

之前做了一个爬虫的程序,因为要通过正则表达式进行数据匹配,网站上数据不是所有都具有值,可能有的时候没有值,这个时候就需要给一个默认值,比如数值类型默认为0,字符串类型默认为string.Empty等等。不能不写,又想偷懒,于是就有了该方法原型。

public static T GetMatchResult<T>(string input, string pattern, int groupIndex = 1){    // 该方法中默认值只有数字:0、字符串:string.Empty两种情况,其他不需考虑    object result = typeof(T).BaseType == typeof(System.ValueType) ? "0" : string.Empty;    Match matchResult = Regex.Match(input, pattern, RegexOptions.Compiled);    if (matchResult.Success)    {        string newResult = matchResult.Groups[groupIndex].Value.Trim();        try        {            result = Convert.ChangeType(newResult, typeof(T));        }        catch (Exception ex)        {            throw new Exception($"{pattern}匹配字符串:{input}失败。\r\n{ex}");        }    }    return (T)Convert.ChangeType(result, typeof(T));}

最开始还有DateTime类型,但是因为匹配到的DateTime类型的字符串更加复杂,只能特殊处理,就把DateTime类型从方法中取消了。这里只是提供方法的思路,如果有其他数据要求,可以根据需求进行更改。

原创粉丝点击