Regular expression substring or left equivalent

Greetings beloved comrades.

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

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

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

This answer The equivalent of a substring as a regular expression sounds promising, but I can't get it to figure it out correctly.

I can create an SQL function to accomplish this, but I would prefer not to clog my server to reformat some lines.

Thanks in advance.

+4
source share
4 answers

You can try the following:

 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 recorded as group 1 and then
  • five digits recorded as group 2

And return a string that replaces this matched text

  • group 1 then
  • literal hyphen followed by
  • group 2 then
  • literal 01 .

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

+11
source

If you can use custom C # scripts, you can use a substring instead:

 string newStr = string.Format("{0}-{1}01", old.Substring(2,2), old.Substring(4)); 
+8
source

I do not think you really need a regular expression. A substring would be better. But if you want only regex, you can use this:

 string newString = Regex.Replace(input, @"^\d{2}(\d{2})(\d+)$", "$1-${2}01"); 

Explanation:

 ^\d{2} // Match first 2 digits. Will be ignored (\d{2}) // Match next 2 digits. Capture it in group 1 (\d+)$ // Match rest of the digits. Capture it in group 2 

Now the required digits are in groups 1 and 2, which you use in the replacement line.

+6
source

Are you even SQL? Pull a few levers and stuff.

0
source

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


All Articles