How to use String.Replace

Quick question:

I have this String m_Author, m_Editor But I have some weird ID stuff within the string so if I do a WriteLine it will look like:

'16;#Luca Hostettler'

I know I can do the following:

    string author = m_Author.Replace("16;#", "");
    string editor = m_Editor.Replace("16;#", "");

And after that I will just have the name, But I think in future I will have other people and other ID's.

So the question: Can I tell the String.Replace("#AndEverythingBeforeThat", "") So i could also have

'14;#Luca Hostettler'

'15;#Hans Meier'

And would get the Output: Luca Hostettler, Hans Meier, without changing the code manually to m_Editor.Replace("14;#", ""), m_Editor.Replace("15;#", "")...?

Jon Skeet
people
quotationmark

It sounds like you want a regex of "at least one digit, then semi-colon and hash", with an anchor for "only at the start of the string":

string author = Regex.Replace(m_Author, @"^\d+;#", "");

Or to make it more reusable:

private static readonly Regex IdentifierMatcher = new Regex(@"^\d+;#");
...
string author = IdentifierMatcher.Replace(m_Author, "");
string editor = IdentifierMatcher.Repalce(m_Editor, "");

Note that there may be different appropriate solutions if:

  • The ID can be non-numeric
  • There may be other ignorable parts and you only want the value after the last hash

people

See more on this question at Stackoverflow