0

I'm a newbie of using regex.

How can I count specific letter on a string ?

var str = "FFFF000FFFCA";

i want an output of 4F303FCA.

I used Regex.Replace(str, @"(.)\1*", m => m.Value.Length + m.Groups[1].Value); but the output is : 4F303F1C1A

Thank you for helping.

1
  • 1
    That output looks right to me. Commented Mar 24, 2015 at 2:05

1 Answer 1

1

Looks like you want to output nothing when there is only one occurrence. You can use "conditional operator" (aka "ternary") to make that choice inline:

string input = "FFFF000FFFCA";
string output = Regex.Replace(input, 
    @"(.)\1*", m => 1 < m.Value.Length ? 
           m.Value.Length.ToString() + m.Groups[1].Value : m.Groups[1].Value);

Note something like 21 could not be decoded back (assuming you are trying to implement version of Run-length encoding).

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

2 Comments

I've added some water to your post so it is not such a dry code sample... Feel free to revert.
Thank you. That's what i want. What if specific letter? Only letter "F". Output is : 4F0003FCA. thanks alot.

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.