[英]How to remove DateTime substring from string
I have a bunch of strings, some of which have one of the following formats:我有一堆字符串,其中一些具有以下格式之一:
"TestA (3/12/10)"
"TestB (10/12/10)"
The DateTime
portion of the strings will always be in mm/dd/yy
format.字符串的
DateTime
部分将始终采用mm/dd/yy
格式。
What I want to do is remove the whole DateTime part including the parenthesis.我想要做的是删除整个 DateTime 部分,包括括号。 If it was always the same length I would just get the index of
/
and subtract that by the number of characters up to and including the (
. But since the mm
portion of the string could be one or two characters, I can't do that.如果它总是相同的长度,我只会得到
/
的索引并将其减去直到并包括(
的字符数。但由于字符串的mm
部分可能是一两个字符,我不能这样做那。
So is there a way to do a .Contains
or something to see if the string contains the specified DateTime
format?那么有没有办法做一个
.Contains
或其他东西来查看字符串是否包含指定的DateTime
格式?
You could use a Regular Expression to strip out the possible date portions if you can be sure they would consistently be in a certain format using the Regex.Replace()
method :如果您可以使用
Regex.Replace()
方法确保它们始终采用某种格式,则可以使用正则表达式去除可能的日期部分:
var updatedDate = Regex.Replace(yourDate,@"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)","");
You can see a working example of it here , which yields the following output :你可以在这里看到它的一个工作示例,它产生以下输出:
TestA (3/12/10) > TestA
TestB (10/12/10) > TestB
TestD (4/5/15) > TestC
TestD (4/6/15) > TestD
You could always use a regular expression to replace the strings您始终可以使用正则表达式来替换字符串
Here is an example这是一个例子
var regEx = new Regex(@"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)");
var text = regEx.Replace("TestA (3/12/10)", "");
Regex could be used for this, something such as:正则表达式可用于此,例如:
string replace = "TestA (3/12/10) as well as TestB (10/12/10)";
string replaced = Regex.Replace(replace, "\\(\\d+/\\d+/\\d+\\)", "");
If I'm understanding this correctly you want to just acquire the test name of each string.如果我正确理解这一点,您只想获取每个字符串的测试名称。 Copy this code to a button click event.
将此代码复制到按钮单击事件。
string Old_Date = "Test SomeName(3/12/10)";
string No_Date = "";
int Date_Pos = 0;
Date_Pos = Old_Date.IndexOf("(");
No_Date = Old_Date.Remove(Date_Pos).Trim();
MessageBox.Show(No_Date, "Your Updated String", MessageBoxButton.OK);
To sum it up in one line of code用一行代码总结一下
No_Date = Old_Date.Remove(Old_Date.IndexOf("(")).Trim();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.