1

Hello Guys i want to get just two value from a big json array using regular expression. E.g: i have this json array

'{"data":"1233","image":"dsfsdfsdfds"."text":"hello world"."name": "java"}' '{"data":"1233df","image":"dsfsdfsdfsdfds"."text":"hello world"."name": "c#"}' '{"data":"1233sds","image":"dsfsdferesdfds"."text":"hello world"."name": "python"}' '{"data":"1sd233","image":"dsfsdfsdfrdfds"."text":"hello world"."name": "c++"}'

I want to get text and name value from this array using regular expression

Mohamed
  • 49
  • 1
  • 1
  • 7
  • 1
    Don't use regex for this. [This is a FAQ.](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) (Structured formats like XML and JSON are like HTML in this context.) – tripleee Jul 23 '18 at 07:11

3 Answers3

4

You should not use regex for parsing JSON. Instead parse JSON through inbuilt functions like parse in case you are using Javascript or different libraries like GSON in case you are using JAVA.

Still, if there is any special requirement to use Regex here, you can use below:

1) For text:

.*?text"\s?:\s?"([\w\s]+)

Output :

Group 1 - 'hello world'

2) For name

.*?name"\s?:\s?"([\w\s]+)

Output:

Group 1 - java

Demo: https://regex101.com/r/74hOO1/1

-- EDIT --

If you want both text and name in one regex, you can use below one, provided text always come before name:

.*?text"\s?:\s?"([\w\s]+).*?name"\s?:\s?"([\w\s]+)

Output:

Group 1.    46-57   `hello world`
Group 2.    68-72   `java`

Demo: https://regex101.com/r/74hOO1/2

Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
  • i want them to be in one regular expresion. I mean that in one regular expression i can get text and name ... like every name and his text – Mohamed Jul 23 '18 at 11:00
  • not worked with my json format... can you see this (?:"name":")(.*?)(?:") and modified like what i am looking for ? – Mohamed Jul 23 '18 at 12:37
  • @Mohamed For the udpated json, I have updated regex as well :) You can check it at https://regex101.com/r/74hOO1/3 – Aman Chhabra Jul 23 '18 at 14:59
2
var data = '{"data":"1233","image":"dsfsdfsdfds", "text":"hello world", "name": "java"}';

var parsedData = JSON.parse(data);

var text = parsedData.text;
var name = parsedData.name;
Anshul Bansal
  • 1,833
  • 1
  • 13
  • 12
0

You can use this regex :

"name"\s?+:\s?+"?([\w+#\s]+)"?

to extract its value here name for example

if you want other key for example text use text instead of name

"text"\s?+:\s?+"?([\w+#\s]+)"?

you'll find the value of the key in the first group See here https://regex101.com/r/1ZSUph/1

Adsl Le
  • 101
  • 1
  • 4