仅当属性有值时应用正则表达式
本文关键字:应用 正则表达式 属性 | 更新日期: 2023-09-27 17:54:03
我有以下方法
public static ProjectListItemViewModel CreateViewModel(P.Project project)
{
return new ProjectListItemViewModel
{
Id = project.Id,
ExpectedResult = Regex.Replace(project.ExpectedResult, @"<[^>]+>| ", string.Empty).Trim().Length > 100 ? Regex.Replace(project.ExpectedResult, @"<[^>]+>| ", string.Empty).Trim().Substring(0, 100) + "..." : Regex.Replace(project.ExpectedResult, @"<[^>]+>| ", string.Empty).Trim(),
Initiator = project.Initiator.FullName,
Status = project.Status.Name,
ProjectManager = project.ProjectManager != null ? project.ProjectManager.FullName :"",
};
}
我的问题是如何应用Regex到ExpectedResult只有当它不是空在最短的可能的方式?
我会稍微改变一下你的风格,只执行一次正则表达式:
// Define other methods and classes here
public static ProjectListItemViewModel CreateViewModel(P.Project project)
{
var rex = new Regex(@"<[^>]+>| ");
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 : "",
};
}
尝试如下:
String Result = !ExpectedResult ?? YourRegEx;
以这种方式,如果值不为空,则直接应用
未测试
在一般情况下,c#
可以正常工作 String Result = ExpectedResult ?? YourRegEx;