0

I have multiple strings in the following format "(space)> sometext > anothertext".

"sometext" and "anothertext" can be anything - they can vary in length and content.

The prefix of each string is always "(space)>", while (space) is any given number of space characters up until a given maximum length.

Examples:

Max prefix length is 10.

 1. "> here is same 1 > sample 1"
 2. "  > here is sample 2 > sample 2 indeed"
 3. "     > a very long spaced prefix > spaced prefix"

I need to align all the prefixes to the same space length. E.g., aligning all to 10 space characters...

 1. "          > here is same 1 > sample 1"
 2. "          > here is sample 2 > sample 2 indeed"
 3. "          > a very long spaced prefix > spaced prefix"

I am using Regex to achieve this goal with the below code:

int padding = 10;
Regex prefix = new Regex(@"^(\s*)>.*");
Match prefix_match = prefix.Match(line);
if (prefix_match.Success == true)
{
    string space_padding = new string(' ', padding - prefix_match.Groups[1].Value.Length);
    return prefix.Replace(line, space_padding);
}
return line;

But I always get as a result is a 10 space length string...

3
  • 2
    Just string.Trim() and add yours spaces, regex seems to be overly complicating this Commented Jun 6, 2019 at 6:55
  • 2
    @TheGeneral: I'm embarrassed :)... why did I think of Regex in first place. Thanks... sometimes keeping it simple is so right Commented Jun 6, 2019 at 6:58
  • 2
    blog.codinghorror.com/… ;) Commented Jun 6, 2019 at 6:58

2 Answers 2

1

This will work.

string text = "   > a very long spaced prefix > spaced prefix";
text = "          " + text.Trim();

Alternatively you could use:

string text = "     > a very long spaced prefix > spaced prefix";
text = new String(' ', 10) + text.Trim();
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a combination of Trim and the String constructor:

string text =  "     > a very long spaced prefix > spaced prefix";
text = new string(' ', 10) + text.Trim();

2 Comments

No. PadLeft's argument is the total length of the string. In that example it will not add any spaces. PadLeft(10) adds leading spaces until the total length is 10 or more. It's the second time this week I've come across this misunderstanding of PadLeft on StackOverflow.
@PalleDue: Thx, I changed my answer.

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.