Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Substring or Left Equivalent

Tags:

c#

regex

Greetings beloved comrades.

I cannot figure out how to accomplish the following via a regex.

I need to take this format number 201101234 and transform it to 11-0123401, where digits 3 and 4 become the digits to the left of the dash, and the remaining five digits are inserted to the right of the dash, followed by a hardcoded 01.

I've tried http://gskinner.com/RegExr, but the syntax just defeats me.

This answer, Equivalent of Substring as a RegularExpression, sounds promising, but I can't get it to parse correctly.

I can create a SQL function to accomplish this, but I'd rather not hammer my server in order to reformat some strings.

Thanks in advance.

like image 496
Eric Hauenstein Avatar asked Nov 28 '22 02:11

Eric Hauenstein


1 Answers

You can try this:

var input = "201101234";
var output = Regex.Replace(input, @"^\d{2}(\d{2})(\d{5})$", "${1}-${2}01");

Console.WriteLine(output); // 11-0123401

This will match:

  • two digits, followed by
  • two digits captured as group 1, followed by
  • five digits captured as group 2

And return a string which replaces that matched text with

  • group 1, followed by
  • a literal hyphen, followed by
  • group 2, followed by
  • a literal 01.

The start and end anchors ( ^ / $ ) ensure that if the input string does not exactly match this pattern, it will simply return the original string.

like image 198
p.s.w.g Avatar answered Dec 15 '22 02:12

p.s.w.g