Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very Simple Regex Question

Tags:

java

regex

I have a very simple regex question. Suppose I have 2 conditions:

  1. url =http://www.abc.com/cde/def
  2. url =https://www.abc.com/sadfl/dsaf

How can I extract the baseUrl using regex?

Sample output:

  1. http://www.abc.com
  2. https://www.abc.com
like image 323
Sunil Avatar asked Feb 03 '23 04:02

Sunil


2 Answers

Like this:

String baseUrl;
Pattern p = Pattern.compile("^(([a-zA-Z]+://)?[a-zA-Z0-9.-]+\\.[a-zA-Z]+(:\d+)?/");
Matcher m = p.matcher(str); 
if (m.matches())
    baseUrl = m.group(1);

However, you should use the URI class instead, like this:

URI uri = new URI(str);
like image 143
SLaks Avatar answered Feb 05 '23 19:02

SLaks


A one liner without regexp:

String baseUrl = url.substring(0, url.indexOf('/', url.indexOf("//")+2));
like image 23
Andreas Dolk Avatar answered Feb 05 '23 20:02

Andreas Dolk