Search code examples
regexregex-lookaroundsregex-groupregex-negation

Can Regex capture a certain string only if a condition is met?


I have this set of data:

  • EndDate":"2024-10-24","Employee":"000A0001","Submitted":"N"
  • EndDate":"2023-10-18","Employee":"000A0001","Submitted":"P"
  • EndDate":"2021-01-02","Employee":"000A0001","Submitted":"J"
  • EndDate":"2022-10-11","Employee":"000A0001","Submitted":"M"
  • EndDate":"2020-09-18","Employee":"000A0001","Submitted":"N"

I only want to capture the EndDate that has a Submitted value of N or M.

The captured EndDate should be:

  • 2024-10-24
  • 2022-10-11
  • 2020-09-18

Solution

  • Yes, you can do this with a regex positive lookahead:

    \d{4}-\d{2}-\d{2}(?=.+"Submitted":"[NM]")
    

    More detail here: Regex lookahead, lookbehind and atomic groups