0

I need a regex to extract server names from below json based on the path. So ideally I should get server1 & server2 the string between https & /upload/image/app as output and ignore the youtube url.

{
    "url1" : "https://server1/upload/image/app/test1.jpg",
    "video" : "https://www.youtube.com/watch?v=K7QaD3l1yQA",
    "type" : "youtube",
    "url2" : "https://server2/upload/image/app/test2.jpg"
}

Tried this, but i know this wont work:

https://(.*?)/upload/image/app
Farhan
  • 752
  • 4
  • 10

2 Answers2

1
^(?:http|https)\:\/\/(.*?)\/(?:.*?)$

This should do the trick. Examples:

<?php
preg_match("/^(?:http|https)\:\/\/(.*?)\/(?:.*?)$/", "https://server1/upload/image/app/test1.jpg", $matches);
echo $matches[1]; //server1
?>

It's not so difficult to work with regex, I suggest you to start learining at least basics because they may be useful

Phate01
  • 2,499
  • 2
  • 30
  • 55
  • My input is not a single URL but the whole json – Farhan Mar 27 '15 at 13:41
  • 1
    I'm not here to do your homework. You asked for a regex and now you have it – Phate01 Mar 27 '15 at 13:42
  • Well the regex changes if you use single url vs the whole json, thanks for the help anyways. – Farhan Mar 27 '15 at 13:46
  • Can't you parse the JSON and then match for all elements? – Phate01 Mar 27 '15 at 13:47
  • Well i want to replace all the server names with another server at one go if thats possible, will parse it as a last resort. – Farhan Mar 27 '15 at 13:49
  • @Farhan You should not be using regex to parse JSON, there are JSON parsers that should be doing this for you, such as [Jackson](https://github.com/FasterXML/jackson). Once you extract the data you want from the JSON, then you would use the regex provided here to extract the domain/server from the URL – JNYRanger Mar 27 '15 at 14:03
  • @JNYRanger Well the JSON i posted is just a small part of a large JSON which is used to create a Java object having deep hierarchy, so instead of navigating the java object and updating the individual url was trying to do it in one go. – Farhan Mar 27 '15 at 14:20
  • 1
    @Farhan Sounds like a terrible idea. Don't take lazy shortcuts like this. This leads to bad code and maintenance issues down the road. Also, regular expression engines are NOT parsers, so don't use them as such. Instead you can combine the technologies to reach your goal. – JNYRanger Mar 27 '15 at 14:23
0

You can try with something like that:

^.*http.*//(\S+)/upload/ima.*

Edit: including a JAVA example:

Pattern p = Pattern.compile("^.*http.*//(\\S+)/upload/ima.*");
Matcher m = p.matcher(nextLine);

if (m.find()) {
    System.out.println(m.group(1));
}

Check: Using Regular Expressions to Extract a Value in Java

Community
  • 1
  • 1
Le Funes
  • 51
  • 4