0

I have a string, shown below

A123459922

I want to remove A and add B with Regex to the end of it. How can I do it using regex

Regex.Replace("A123459922","(\w{1})(\d*)");

I don't know exactly how can I remove the first character and Add 'B' to the end of it? to ended up something like this

123459922B
4
  • 3
    what's wrong with Substring() ? Commented Feb 26, 2013 at 9:26
  • Is B needed to be added only when there's an A in the beginning? Or always regardless? Commented Feb 26, 2013 at 9:27
  • I see , but just keen to know how regex can apply to this issue Commented Feb 26, 2013 at 9:28
  • So long as you don't care about any A, you can also use string.Replace which is faster but will also match any and all A even the ones you might want to keep. Commented Feb 26, 2013 at 9:28

3 Answers 3

2

I'll use the same regex of your question.

You could look at this (for more complex situations)

Regex.Replace("A123459922",@"(\w{1})(\d*)", m => m.Groups[2].Value + "B");

See the 3rd parameter of the Replace method. It is a MatchEvaluator, which receives a Match and returns the replacement string. The above expressions is equivalent to:

private static void Main()
{
    Regex.Replace("A123459922",@"(\w{1})(\d*)", Evaluator);
}

private static string Evaluator(Match m) {
    return m.Groups[2].Value + "B";
}

You're basically saying: I want to replace the entire match by the 2nd group + the B character

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

1 Comment

The question, while unclear, does mention "the first character". Shouldn't answers take this into account?
2

According to your given input and output string example, you can do this simply with Substring():

var newString = myString.Substring(1) + "B";

Comments

1

Try using this regex:

Regex.Replace("A123459922", @"\w(.*)", "$1B");

Comments

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.