regex - Java Regexp to match domain of url -


i use java regex match domain of url, example, www.table.google.com, 'google' out of url, namely, second last word in url string.

any appreciated !!!

it depends on complexity of inputs...

here pretty simple regex:

.+\\.(.+)\\..+ 

it fetches inside dots \\..

and here examples pattern: https://regex101.com/r/l52oz6/1. can see, works simple inputs not complex urls.

but why reinventing wheel, there plenty of libraries correctly parse complex url. sure, simple inputs small regex build. if not solve problem inputs please callback, adjust regex pattern then.


note can use simple splitting like:

string[] elements = input.split("\\."); string secondtolastelement = elements[elements.length - 2]; 

but don't forget index-bound checking.


or if search quick solution walk through input starting last position. work way through until found first dot, continue until second dot found. extract part input.substring(index1, index2);.

there delegate method purpose, namely string#lastindexof (see documentation).

take @ code snippet:

string input = ... int indexlastdot = input.lastindexof('.'); int indexsecondtolastdot = input.lastindexof('.', indexlastdot); string secondtolastword = input.substring(indexlastdot, indexsecondtolastdot); 

maybe bounds off 1, haven't tested code, idea. don't forget bound checking.

the advantage of approach is fast, can directly work on internal structures of strings without creating copies.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -