Search code examples
regexregexp-replace

Select the second instance of a character with regex


I want to select the second 'M' in the following string using regex. So, the M after T.

P3Y6M4DT12H30M5S

Sometimes the string looks like one of these:

PT12H30M5S
PT12H30M5.234523S

I've tried multiple expressions and searched for a similar case but couldn't find anything.

Could someone help me build an expression to select the M after T so I can use it in my regex replace function?


Solution

  • (?!.+T.+)(M)
    

    Selects everything until the first T and then selects everything until the first M and captures it.

    Example: https://regex101.com/r/sPbQQj/2