Format regular expression string in C #

I would like to format a string that looks like this:

BPT4SH9R0XJ6 

In what looks like this

 BPT4-SH9R-0XJ6 

The string will always consist of 12 letters and numbers.

Any advice would be much appreciated, thanks

+6
source share
11 answers

Try Regex.Replace(input, @"(\w{4})(\w{4})(\w{4})", @"$1-$2-$3");

Regular expression is often ridiculed, but is a pretty neat way to do what you need. It can be expanded to more complex requirements that are difficult to fulfill with string methods.

+18
source

You can use "(.{4})(.{4})(.{4})" as your expression and "$1-$2-$3" as your replacement. This, however, is hardly useful for regexp: you can make it a lot easier with Substring .

 var res = s.Substring(0,4)+"-"+s.Substring(4,4)+"-"+s.Substring(8); 
+5
source

If the rule is to always share three blocks of four characters, there is no need for reg exp:

 str.Substring(0,4) + "-" + str.Substring(4,4) + "-" + str.Substring(8,4) 
+4
source

It would seem that the combination of String.Concat and string.Substring should take care of everything you need.

+3
source
  var str = "BPT4SH9R0XJ6"; var newStr = str.Substring(0, 4) + "-" + str.Substring(4, 4) + "-" + str.Substring(8, 4); 
+2
source

Any reason you want to make regex? you can just insert hyphens:

 string s = "BPT4SH9R0XJ6"; for(int i = 4; i < s.length; i = i+5) s = s.Insert(i, "-"); 

This would continue to add hyphens every 4 characters, would not fail if the string was too short / long / etc.

+1
source
 return original_string.SubString(0,4)+"-"+original_string.SubString(4,4)+"-"+original_string.SubString(8,4); 
+1
source
 string str = @"BPT4SH9R0XJ6"; string formattedString = string.Format("{0}-{1}-{2}", str.Substring(0, 4), str.Substring(4,4), str.Substring(8,4)); 
+1
source

This works with any string length:

  for (int i = 0; i < (int)Math.Floor((myString.Length - 1) / 4d); i++) { myString = myString.Insert((i + 1) * 4 + i, "-"); } 
+1
source

Completed by upp using this

 var original = "BPT4SH9R0XJ6".ToCharArray(); var first = new string(original, 0, 4); var second = new string(original, 4, 4); var third = new string(original, 8, 4); var mystring = string.Concat(first, "-", second, "-", third); 

thanks

0
source

If you are guaranteed the text you are working on is a 12-character code, then why not just use a substring? Why do you need Regex?

 String theString = "AB12CD34EF56"; String theNewString = theString.Substring(0, 4) + "-" + theString.Substring(4, 4) + "-" + theString.Substring(8, 4);' 
0
source

Source: https://habr.com/ru/post/913967/


All Articles