简体   繁体   中英

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.

What I want to do is remove the whole DateTime part including the parenthesis. 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.

So is there a way to do a .Contains or something to see if the string contains the specified DateTime format?

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 :

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

Use a RegEx for this. I recommend:

\(\d{1,2}\/\d{1,2}\/\d{1,2}\)

See RegExr for it working.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM