-1

I need to do two things with strings:
A. Remove the file extension
B. Remove the '-' from the dates.

An example of an uploaded string is:

ifrs_au-cor_2013-03-12.xsd

I can't just do a replace on '-' because the first part of the string contains a '-' that I don't want removed, only the date ones. However, the date will always be in YYYY-MM-DD format and it will be at the end with the extension.

Currently I only have the following code to remove the extension from the string:

String xsdfnameNoExtNoSlash = xsdfname;
int fileExtPos = xsdfname.LastIndexOf(".");
if (fileExtPos >= 0 )
  xsdfnameNoExtNoSlash = xsdfname.Substring(0, fileExtPos);

Is there any way to do both of these operations in one go?

2
  • I guess a regular expression may help here, but to be honest, what's the advantage of doing this in 1 go. I don't think this is really needed. Commented Mar 12, 2013 at 18:57
  • Not at all a requirement just, no problem with two different strings. Was just wondering if there was a regex or some way to do it in one. Commented Mar 12, 2013 at 19:04

2 Answers 2

2
var name = Path.GetFileNameWithoutExtension(name);
return Regex.Replace(name, @"(?<!\d)(\d\d\d\d)-(\d\d)-(\d\d)(?!\d)", "$2$3$4");

This first removes the extension (if present), and then finds all dates and removes slashes from them.

The regex uses lookahead and lookbehind to ensure that something like "92012-01-019" is not considered a date. Anything other than a digit is accepted as a date boundary. You can tweak this if necessary, for example, if "92012-01-019" should, in fact, be changed to "9201201019" then you can just remove the lookahead/lookbehind (and change the numbers in the replacement string).

I think it's easiest to remove the extension as a separate step, rather than trying to do it all in one go.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice, and your conclusion is also correct in my opinion. Doing it with a regex makes it almost unreadable :)
running the code is giving me: ifrs_au-cor_0312$4 - its removing the year and adding a $4 also.
0
string noslash = withslash.Replace('-', '');
string noextension = Path.GetFileNameWithoutExtension(xsdfname);

2 Comments

Even if the Replace method were applicable here, the string version would have to be used, seeing as there is no empty character literal. See stackoverflow.com/questions/3670505/… for more information.
Oops, missed the requirement. In that case, you woud need a regex replace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.