4

I have a question regarding replacing some characters with regex or any other best practice or efficient way.
Here is what I have as input, it has mostly the same form: A/ABC/N/ABC/123
The output should look like this: A_ABC_NABC123, basically the first 2 / should be changed to _ and the rest removed.
Of course i could do with some String.Replace. etc one by one, but I don't think it is a good way to do that. I search for a better solution.

So how to do it with Regex?

4

2 回答 2

7

This will do it, although there may be a simpler way:

static class CustomReplacer
{
    public static string Replace(string input)
    {
        int i = 0;
        return Regex.Replace(input, "/", m => i++ < 2 ? "_" : "");
    }
}

var replaced = CustomReplacer.Replace("A/ABC/N/ABC/123");

I've wrapped the code like this to make sure you don't accidentally the int variable.

Edit: There's also this overload which stops after a certain number of replacements, but you'd have to do it in two steps: replace the first two / with _, then replace the remaining / with nothing.

于 2012-11-28T11:20:49.490 回答
0

Try this:

string st = "A/ABC/N/ABC/123";
string [] arrStr = st.Split(new char[] { '/' });
st = string.Empty;
for (int i = 0; i < arrStr.Length; i++)
{
    if (i < 2)
        st += arrStr[i] + "_";
    else
        st += arrStr[i];
}
于 2012-11-28T11:26:38.523 回答