Convert "9954-4740-4491-4414" to "99: 54: 47: 40: 44: 91: 44: 14" using regular expressions

If the title is not clear enough, here is a procedural approach to the problem:

[TestMethod] public void Foo() { var start = "9954-4740-4491-4414"; var sb = new StringBuilder(); var j = 0; for (var i = 0 ; i < start.Length; i++) { if ( start[i] != '-') { if (j == 2) { sb.AppendFormat(":{0}", start[i]); j = 1; } else { sb.Append(start[i]); j++; } } } var end = sb.ToString(); Assert.AreEqual(end, "99:54:47:40:44:91:44:14"); } 
+4
source share
5 answers

If you are using C # 4, you need the following:

 string result = string.Join(":", Regex.Matches(start, @"\d{2}").Cast<Match>()); 

For C # 3 you need to provide string[] for the connection:

 string[] digitPairs = Regex.Matches(start, @"\d{2}") .Cast<Match>() .Select(m => m.Value) .ToArray(); string result = string.Join(":", digitPairs); 
+5
source

I agree, "why bother with regular expressions?"

 string.Join(":", str.Split('-').Select(s => s.Insert(2, ":")); 
+4
source

Regex.Replace version, although I like that Mark's answer is better:

 string res = Regex.Replace(start, @"(\d{2})(\d{2})-(\d{2})(\d{2})-(\d{2})(\d{2})-(\d{2})(\d{2})", @"$1:$2:$3:$4:$5:$6:$7:$8"); 
+2
source

After some time of experimentation, I found a way to do this using one regex that works with input of unlimited length:

 Regex.Replace(start, @"(?'group'\d\d)-|(?'group'\d\d)(?!$)", @"$1:") 

When using the named groups (tags (?'name') ) with the same name, the entries are stored in the same group. Thus, it is possible to replace individual matches with the same value.

It also uses negative browsing (stuff (?!) ).

+1
source

You do not need them: separate the characters "-" and insert a colon between each pair of numbers. If I do not understand the desired output format.

0
source

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


All Articles