Ram
Ram

Reputation: 731

regex to fetch number from json

How to get the required format text output from json payload using regexp

"number" : 4aac4c35-8e3e-4730-8364-381884d6f20f:OP:QUAL:117804471:PON:false

what is the expression to get the output like following

"number" : 117804471

could you please help.

I tried the following; but it didn't work; I am newbie to this.

([\"]token[\"][\s]*:[\s]*)?([0-9]{9})

Upvotes: -3

Views: 996

Answers (2)

PJProudhon
PJProudhon

Reputation: 825

Still not very sure of what you exactly want or need, but let's give a try, based on what you wrote here and in your sample.

Receiving some string respecting the following:

  • Starting with a double-quote enclosed token.
  • Followed by a colon, occasionally surrounded by any number of spacing characters.
  • Followed on the right part by a suit of colon separated tokens.
  • One of those being composed of numbers only.

Trying to replace that input by only:

  • Double-quote enclosed token.
  • Followed by a colon, surrounded spaces kept.
  • Immediately followed by the number only token.

You could then use the following pattern to get your match: ^(?<token>"[^"]+"\s*:\s*)(?:\d*[^\d:][^:]*:)*(?<number>\d+)(?::[^:]*)*$.

The following should then be used to replace: $1$2.

Demo here.

That may be simplified or adapted when knowing additional rules.

Upvotes: 1

Patrick Janser
Patrick Janser

Reputation: 4244

Yes, as @PJProudhon says, we are lacking some precisions to help you.

If you just want to extract the number without using some capturing groups, you could go with this regular expression: (?<=:)\d+(?=:\w+:(?:true|false))

Quick explanation:

  • (?<=:) is a positive lookbehind to find the : char.
  • \d+ is to get a number of at least 1 decimal or more.
  • (?=:\w+:(?:true|false)) is a positive lookahead to find a :, a word, a : and then true or false.

Small test with multiple values here: https://regex101.com/r/1nRnct/2

Hope this can help you.

Upvotes: 2

Related Questions