Home > Software engineering >  Regex to match a pattern within quotes
Regex to match a pattern within quotes

Time:10-01

I'm trying to match and substitute a pattern.

Test String: {1-Emp Name: "John", "2-Emp pat" : 1123,"3-Emp lwd" : 20}, "4-Emp Pat" : 1234}

I'm trying to match the pattern with the word "pat" from the test string and substitute

Expected Result: {1-Emp Name: "John", "matched Pattern" : 1123,"3-Emp lwd" : 20}, "matched Pattern" : 1234}

My regex: ". ?(?i)Pat. ?(?=:)

CodePudding user response:

You can use

Regex pattern: (?i)"[^"]* Pat\b[^"]*("\s*:)
Replacement pattern: "matched pattern$1

See the regex demo. Details:

  • (?i) - case insensitive inline modifier
  • " - a " char
  • [^"]* - zero or more chars other than "
  • Pat - space Pat word
  • \b - word boundary
  • [^"]* - zero or more chars other than "
  • ("\s*:) - Group 1 ($1): ", zero or more whitespaces, :.
  • Related