我有一个输出字符串,它将包含一个工作日(星期一、星期二等)。
例如,
"Some tex may appear before week day, Monday, will only be one occurrence of the weekday"
如何从字符串中检索工作日?
我可以使用 IF 语句链来查看字符串是否包含工作日,但想知道是否有更简洁的方法?
这将构建一个正则表达式,它将找到一周中的某一天。
var pattern = string.Format("({0})", string.Join("|", Enum.GetValues(typeof (DayOfWeek)).OfType<DayOfWeek>()));
var match = Regex.Match("some text here, Thursday maybe text here", pattern, RegexOptions.IgnoreCase);
Assert.AreEqual("Thursday", match.Value);
我会做一些寻找当天索引的事情,然后从那里拉出来。就像是:
int first = str.IndexOf("Thursday");
int last = str.LastIndexOf("Thursday");
string day = str.Substring(first, last);
代码可能不是 100% 正确,但类似的东西应该可以工作。如果超过一天,您显然必须每天都这样做。
检查它是否存在于字符串中
string text = "some text here, Thursday maybe text here";
if (text.Contains("thursday")) // Make text to lower case before checking
{
...
}
删除它
text = text.Replace("thursday", ""); // Regex would be better to make it case-insensitive
一周中的所有日子都这样做。
假设不考虑这种情况并且只发生一种情况:
string found = "";
string myString = "some text here, Thursday maybe text here";
foreach (string str in myString.Split())
foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
if(day.ToString() == str) found = str;
int intCounter = 0;
string strWeekName = "";
string strContent = "Some text wednesday";
strContent = strContent.ToUpper;
while (intCounter < 7) {
if (strContent.Contains(DateAndTime.WeekdayName(intCounter).ToUpper())) {
strWeekName = DateAndTime.WeekdayName(intCounter);
break;
}
intCounter++;
}
MsgBox "Weekday " + strWeekName;