C#仅在属性有值时才应用正则表达式

时间:2015-06-08 10:10:34

标签: c# asp.net regex asp.net-mvc

我有以下方法

public static ProjectListItemViewModel CreateViewModel(P.Project project)
    {
        return new ProjectListItemViewModel
        {
            Id = project.Id,
            ExpectedResult = Regex.Replace(project.ExpectedResult, @"<[^>]+>|&nbsp;", string.Empty).Trim().Length > 100 ? Regex.Replace(project.ExpectedResult, @"<[^>]+>|&nbsp;", string.Empty).Trim().Substring(0, 100) + "..." : Regex.Replace(project.ExpectedResult, @"<[^>]+>|&nbsp;", string.Empty).Trim(),
            Initiator = project.Initiator.FullName,
            Status = project.Status.Name,
            ProjectManager = project.ProjectManager != null ? project.ProjectManager.FullName  :"",
        };
    }

我的问题是如何将Regex应用于ExpectedResult只有在最短的时间内不为空?

2 个答案:

答案 0 :(得分:0)

我稍微改变你的风格,只执行一次正则表达式:

// Define other methods and classes here
public static ProjectListItemViewModel CreateViewModel(P.Project project)
{
    var rex = new Regex(@"<[^>]+>|&nbsp;");
    var expected = rex.Replace(project.ExpectedResult ?? string.Empty, string.Empty).Trim();

    return new ProjectListItemViewModel
    {
        Id = project.Id,
        ExpectedResult = expected.Length > 100 ? expected.Length.Substring(0, 100) : expected,
        Initiator = project.Initiator.FullName,
        Status = project.Status.Name,
        ProjectManager = project.ProjectManager != null ? project.ProjectManager.FullName : "",
    };
}

答案 1 :(得分:0)

尝试这样:

String Result = !ExpectedResult ?? YourRegEx;

这样,如果值不为空,则直接应用。

未经测试

这里通常c#

工作正常

String Result = ExpectedResult ?? YourRegEx;