String.Format

I have a string, for example, "123abcdefg."  I would like to format the string and assign it to a textbox.  The format I would like is, for example "123-abc-d-efg."  I have tried using String.Format, but such custom formats seem to apply only to numbers, not to strings.  

Is there any other way of formatting the string, short of using left() and mid()

Thanks for the help.


Answer this question

String.Format

  • JohnHart_MS

    Yes, you can use RegEx.Replace to manipulate strings:

    Regex.Replace("abc1234567", "([a-zA-Z]{3})(\d{3})(\d{1})(\d{3})", "$1-$2-$3-$4")

    will generate "abc-123-4-567". Use brackets "(" and ")" to define logical groups and refer to them as $1, $2 and so on. You can also use group names to make things easier to read later:

    Regex.Replace("abc1234567", "( <GroupA>[a-zA-Z]{3})( <First>\d{3})( <Second>\d{1})( <Third>\d{3})", "${GroupA}-${First}-${Second}-${Third}")


  • opticyclic

    There are a number of MS moderators on this site maybe they know.

    But regarding RegEx expressions, I think I know how you feel about them. It's almost like a completely new language of garbel-d-guke that we have to learn. That was my first impression.

    On the other hand, RegEx is widely used in many different languages and isn't new. My guess is that, like MS adopting XML as a core standard, they're doing the same with RegEx for validation because it already is a standard.

    It's worth learning. Good luck!

  • Luis H Mora

    Thank you for your timely replies and offer to help.  I will review the principles and rules of regular expressions and try to begin applying them.

    One question, however.  Would you know the reason why Microsoft decided to remove the simple string formatting contructs of VB6

  • GeriB

    Cool!  I'll have to play with that some more.


  • Chimere77

    And here's that regular expression that Mike was referring to:

    \d{3}-[A-Za-z]{3}-[A-Za-z]{1}-[A-Za-z]{3}$

    This one matches the example of "123-abc-d-efg" you provided.

    If you choose to use RegEx (regular expressions) and need some help, let me know and I'll create an example for you.

  • KiwiDev

    Regular expressions are pretty darn cool, but can they do anything other than validation   In the above example, Hammert wants to take the string 123abcdefg and format it into a specific set of positions and dashes.  Can you use regular expressions to do this formatting for you

    I'm thinking that you would have to use regular expressions to validate the raw 123abcdefg format, and then do your own string manipulation code to turn it into 123-abc-d-efg, and then possibly use regular expressions again to verify that final displayformat.

    I guess what I'm asking is whether you can use regular expressions to do string manipulation, not just validation.


  • slyi

    You could use Regular Expressions.
  • String.Format