Regex substitution for substring from position n to m and remove leading 0

Viewed 53

I have the following string

020075307354H         021133360876      981497910079937800ABC              CDE              FGH                THY                0M19780403015001O+2¹qujzh_¢o\piVN¤«²µerNA¥\^?©E|=V_®¢Zu<£;Æ^TV½IÌc¤±·Gl.ÁEÊO·9y¹Bs¾Ë©ºFT¥*ÉA¬=iÚÒ®{æ*»¨;ÄNÕ®Ûòæ¦'Ñ…9>ÙYKè¹t/R{(>ÔÕBã2½7q¹|u…nztf~¦spw_ZX£\¦~Qa²mn¡¨QX«W±¯¯¦¨d£¾}·`B¶M}Qc|AµOÇ~Äd¤·¯HÇaI_¶²ÂÆYC?xÄR²>½HpÃjÁNLifm@ÕEí¾)ZvÇÊzØ)D&¦áÑM¡ç…1F¥Åh9R[9Fä¤Ãå<÷¼T}Ã…©ÎCDNs«E`É?¤eñ/ï´¯Åíÿt

and I want to use 1 Regex substitution to do the following 2 tasks:

  1. Get the substring from position 49 to 58 -> 0079937800
  2. Strip leading zeros from this substring -> 79937800

The desired end result is 79937800.

I figured out, that I can substitute the substring of task 1 with .{48}(.{10}).+.

The second task of removing leading I figured I can get using (\b0*([1-9][0-9]*|0)\b) , but how can I combine both tasks and get a working substitution string?

1 Answers

You can capture the "marker" that follows the 10-character string in a capture group in a positive lookahead, then match the desired substring with an arbitrary number of leading zeroes, and follow it with another positive lookahead to ensure that it is followed by the marker captured in the first capture group. The desired substring will then be in the second capture group:

^.{48}(?=.{10}(.*))0*(.*?)(?=\1)

Demo: https://regex101.com/r/Q61KYJ/1

Since you commented that the requirement for a substitution is mandated by your software, you can simply add .* at the end of the above regex and substitute the match with the second capture group:

^.{48}(?=.{10}(.*))0*(.*?)(?=\1).*

Demo: https://regex101.com/r/FcRAGB/1

Related