Home > Blockchain >  regular expression match and replace or match and split
regular expression match and replace or match and split

Time:09-11

I'm having trouble reusing the matched part of a regular expression. The issue isn't finding with the regular expression, but using it to replace or split a string using the matched part.

Below the before and after I'm looking fore.

before:

AB_C_DE01FGHI0123456789_XXX_202201.pdf

after:

AB_C_DE01FGHI0123456789_XXX_2022-01.pdf

The only difference is that it splits the 6 digits in a group of 4 and 2 and concatenates it with a dash '-'

202201 to 2022-01

Here is the regex string I'm using to match the 6 digits and '.pdf'.

\d{6}(?:.pdf)

Which will match:

202201.pdf

And now for the difficult part, I want to reuse the match part and replace/split it so that the new string looks like this:

AB_C_DE01FGHI0123456789_XXX_2022-01.pdf

So my questions boils down to how to use regular expressions in the replace part.

CodePudding user response:

You can search using this regex with 2 capture groups:

(_\d{4})(\d{2}\.pdf$)

Replace it with:

$1-$2

RegEx Demo

Breakup:

  • (_\d{4}): Capture group #1 to match _ followed by 4 digits
  • (\d{2}\.pdf$): Capture group #2 to match 2 digits followed by .pdf before end
  • Related