how to use a regular expression to extract json fields?

前端 未结 4 1727
天涯浪人
天涯浪人 2020-12-03 02:20

Beginner RegExp question. I have lines of JSON in a textfile, each with slightly different Fields, but there are 3 fields I want to extract for each line if it has it, ignor

4条回答
  •  误落风尘
    2020-12-03 02:48

    This question is a bit older, but I have had browsed a bit on my PC and found that expression. I passed him as GIST, could be useful to others.

    EDIT:

    # Expression was tested with PHP and Ruby
    # This regular expression finds a key-value pair in JSON formatted strings
    # Match 1: Key
    # Match 2: Value
    # https://regex101.com/r/zR2vU9/4
    # http://rubular.com/r/KpF3suIL10
    
    (?:\"|\')(?[^"]*)(?:\"|\')(?=:)(?:\:\s*)(?:\"|\')?(?true|false|[0-9a-zA-Z\+\-\,\.\$]*)
    
    # test document
    [
      {
        "_id": "56af331efbeca6240c61b2ca",
        "index": 120000,
        "guid": "bedb2018-c017-429E-b520-696ea3666692",
        "isActive": false,
        "balance": "$2,202,350",
        "object": {
            "name": "am",
            "lastname": "lang"
        }
      }
    ]
    

提交回复
热议问题