WS1234
WS1234

Reputation: 11

Building a Regex String - Any assistance provided

Im very new to REGEX, I understand its purpose, but Im struggling to yet fully comprehend how to use it. Im trying to build a REGEX string to pull the A8OP2B out from the following (or whatever gets dumped in that 5th group).

{"RfReceived":{"Sync":9480,"Low":310,"High":950,"Data":"A8OP2B","RfKey":"None"}}

The other items in above line, will change in character length, so I cannot say the 51st to the 56th character. It will always be the 5th group in quotation marks though that I want to pull out.

Ive tried building various regex strings up, but its still mostly a foreign language to me and I still have much reading to do on it.

Could anyone provide me a working example with the above, so I can reverse engineer and understand better?

Thanks

Upvotes: -1

Views: 32

Answers (1)

zer00ne
zer00ne

Reputation: 43880

Demo 1: Reference the JSON to a var, then use either dot or bracket notation.

Demo 2: Using RegEx is not recommended, but here's one in JavaScript:

/\b(\w{6})(?=","RfKey":)/g

First Match

  1. non-consuming match: :"A

    meta border: \b: A non-word=:, any char=", and a word=A

  2. consuming match: A8OP2B

    begin capture: (, Any word =\w, 6 times={6} end capture: )

  3. non-consuming match: ","RfKey":

    Look ahead: (?= for: ","RfKey": )


Demo 1

var obj = {"RfReceived":{"Sync":9480,"Low":310,"High":950,"Data":"A8OP2B","RfKey":"None"}};

var dataDot = obj.RfReceived.Data;

var dataBracket = obj['RfReceived']['Data'];

console.log(dataDot);

console.log(dataBracket)


Demo 2

Note: This is consuming a string of 3 consecutive patterns. 3 matches are expected.

var rgx = /\b(\w{6})(?=","RfKey":)/g;

var str = `{"RfReceived":{"Sync":9480,"Low":310,"High":950,"Data":"A8OP2B","RfKey":"None"}},{"RfReceived":{"Sync":8080,"Low":102,"High":1200,"Data":"PFN07U","RfKey":"None"}},{"RfReceived":{"Sync":7580,"Low":471,"High":360,"Data":"XU89OM","RfKey":"None"}}`;

var res = str.match(rgx);

console.log(res);

Upvotes: 1

Related Questions