在一个字符串中获取星期几

时间:2012-10-05 19:23:27

标签: c# regex

我有一个输出字符串,其中包含一个工作日(星期一,星期二等)。

例如,

"Some tex may appear before week day, Monday, will only be one occurrence of the weekday"

如何从字符串中检索工作日?

我可以使用一系列IF语句来查看字符串是否包含工作日,但想知道是否有更简洁的方法?

5 个答案:

答案 0 :(得分:3)

这将构建一个可以找到一周中某一天的正则表达式。

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);

答案 1 :(得分:0)

我会做一些寻找当天索引的东西,然后从那里拉出来。类似的东西:

int first = str.IndexOf("Thursday");
int last = str.LastIndexOf("Thursday");
string day = str.Substring(first, last);

代码可能不是100%正确,但类似的东西应该有效。如果有一天以上,你显然必须每天都这样做。

答案 2 :(得分:0)

检查字符串中是否存在

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

一周中的所有日子都这样做。

答案 3 :(得分:0)

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;

答案 4 :(得分:0)

假设案件未被考虑&amp;只发生一个实例:

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;