0

when a textbox contains only digits I am using padleft method,here my textbox contains alphanumeric text,for this I need to do padding with zero's.

textBox1.Text = textBox1.Text.PadLeft(5, '0'); 

This line works when textbox contains digits like 1.output is 00001. Now if my text in textbox is A1.output should be A00001. if AB1 Output should be AB00001. the number of digits should be 5

2 Answers 2

1

You can use RegEx for this:

var parts = Regex.Split(textBox1.Text, "(\\d+)"); textBox1.Text = parts.Length<2 ? parts[0] : parts[0] + parts[1].PadLeft(5, '0'); 

Update: if you don't want to use Regex, you can try the following code:

int i = 0; for(;i < textBox1.TextLength; i++){ if(char.IsDigit(textBox1.Text[i])) break; } textBox1.Text = textBox1.Text.Substring(0,i) + textBox1.Text.Substring(i).PadLeft(5,'0'); 
Sign up to request clarification or add additional context in comments.

4 Comments

Its working but total number of digits should be 5, like this,when I entered AB1,AB00001 should be the output
@user2897388 It was because your question was wrong, now you edited it and the answer is much simpler, see the update.
can you explain me without using Regular Expression for the same process
0

You can use this code. I assumed you wanted to split letters from numbers. It will also work if you have only digits or numbers.

string input = "A1"; var match = Regex.Match(input, @"([a-zA-Z]*)(\d*)"); string group1 = match.Groups.Count > 1 ? match.Groups[1].Value : ""; string group2 = match.Groups.Count > 2 ? match.Groups[2].Value : ""; string output = group1 + group2.PadLeft(6 - group1.Length - group2.Length, '0'); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.