Last active
May 6, 2024 20:10
-
-
Save amlang/3293401dd9a745b5f3d7 to your computer and use it in GitHub Desktop.
Regex find key and value pair in JSON formated string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# PHP / Ruby | |
# Regex find key and value pair in JSON formated string | |
# Match 1: Key | |
# Match 2: Value | |
# https://regex101.com/r/zR2vU9/4 | |
# http://rubular.com/r/KpF3suIL10 | |
# http://stackoverflow.com/questions/14349889/how-to-use-a-regular-expression-to-extract-json-fields/35129815#35129815 | |
(?:\"|\')(?<key>[^"]*)(?:\"|\')(?=:)(?:\:\s*)(?:\"|\')?(?<value>true|false|[0-9a-zA-Z\+\-\,\.\$]*) | |
# test string | |
[ | |
{ | |
"_id": "56af331efbeca6240c61b2ca", | |
"index": 120000, | |
"guid": "bedb2018-c017-429E-b520-696ea3666692", | |
"isActive": false, | |
"balance": "$2,202,350", | |
"object": { | |
"name": "am", | |
"lastname": "lang" | |
} | |
} | |
] | |
Nice! But if the value is a email, it fails...
\@
must be added to the values set
(?i)["'](?<key>[^"]*)["'](?:\:)["'\{\[]?([\r\n]?\t+\")?(?<value>\w(?:[\w!#-'*+\/=?^-~-]\.?)+\w+@(?:(?:\w[a-z\d\-]+\w)\.)+[a-z]{2,10}|true|false|[\w+-,.$]*)(",[\r\n])?(?2)?(?J)(?<value>(?&value))?
Give this a go to:
- Match on email addresses.
- Make it case insensitive.
- Match on multiple values for the same key.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! But if the value is a email, it fails...
\@
must be added to the values set