Search code examples
regexstringkeyvaluepair

Regex extraction of substrings ignoring internal character used to match


I'm matching a string of a key value pair between characters "" with "(.*?)" how can I ignore any extra " characters within the value part.

example string {"1"=>"email@example.com"}


Solution

  • You may use

    String pat = "(?<=\\{|=>)\"(.*?)\"(?=\\}|=>)";
    

    See the regex demo

    Details

    • (?<=\{|=>) - a positive lookbehind that matches a location immediately preceded with { or =>
    • " - a double quotation mark
    • (.*?) - Group 1: any zero or more chars other than line break chars, as few as possible
    • " - a double quotation mark
    • (?=\}|=>) - a positive lookahead that matches a location immediately followed with } or =>.