I'd like to extract URL from hi there this is a URL String http://mytest.com.
I tried to use EditText.getURLs but it didn't work for me.
EditText.setText("hi there this is a URL String http://stackoverflow.com");
EditText.getURLs.toString();
How can I get URL from EditText?
Here is the function:
//Pull all links from the body for easy retrieval
private ArrayList pullLinks(String text) {
ArrayList links = new ArrayList();
String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
urlStr = urlStr.substring(1, urlStr.length() - 1);
}
links.add(urlStr);
}
return links;
}
change input type of your EditText ---- android:inputType="textUri"
and get your url using --- String url=edittext.getText().toString();
Check this library: (https://github.com/robinst/autolink-java)
compile "org.nibor.autolink:autolink:0.7.0"
Working fine with Android.
Example:
LinkExtractor linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL))
.build();
Iterable<LinkSpan> links = linkExtractor.extractLinks(String_with_Link");
LinkSpan link = links.iterator().next();
link.getType(); // LinkType.URL
link.getBeginIndex(); // 17
link.getEndIndex(); // 32
final_Url = String_with_Link.substring(link.getBeginIndex(), link.getEndIndex());
Related
I am using URI Builder class to build this url
http://image.tmdb.org/t/p/w185//qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
Here is my code:
`final String TMDB_results = "results";
final String TMDB_title = "original_title";
final String TMDB_poster = "backdrop_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray resultArray = moviesJson.getJSONArray(TMDB_results);
String[] resultnameStrs = new String[resultArray.length()];
String[] resultposterStrs = new String[resultArray.length()];
for (int i = 0; i < resultArray.length(); i++) {
String moviename;
String movieposter;
// Get the JSON object in which movie title is there
JSONObject movietitle = resultArray.getJSONObject(i);
moviename = movietitle.get(TMDB_title).toString();
movieposter = movietitle.get(TMDB_poster).toString();
//Poster URL Builder
Uri posterbuiltUri = Uri.parse("http://image.tmdb.org/t/p/w185/").buildUpon()
.appendPath(movieposter).build();
String PosterUrl = posterbuiltUri.toString();
resultposterStrs[i] = PosterUrl;
resultnameStrs[i] = moviename;
}
But the URL being build is
http://image.tmdb.org/t/p/w185/%2Fqjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
Here is a part of JSON String from which I am retrieving data:
{"page":1,"results":[{"adult":false,"backdrop_path":"/kvXLZqY0Ngl1XSw7EaMQO0C1CCj.jpg","genre_ids":[28,12,878],"id":102899,"original_language":"en","original_title":"Ant-Man","overview":"Armed with the astonishing ability to shrink in scale but increase in strength, con-man Scott Lang must embrace his inner-hero and help his mentor, Dr. Hank Pym, protect the secret behind his spectacular Ant-Man suit from a new generation of towering threats. Against seemingly insurmountable obstacles, Pym and Lang must plan and pull off a heist that will save the world.","release_date":"2015-07-17","poster_path":"/D6e8RJf2qUstnfkTslTXNTUAlT.jpg","popularity":54.222073,"title":"Ant-Man","video":false,"vote_average":6.9,"vote_count":1859},.......
I think the '/' is being encoded to '%2F'. Is there any way to stop that?
Any help regrading this is appreciated.
appendPath is encoding the / character from your image path -- you're likely seeing %2F as the encoded (aka URL safe) alternative. Your quickest bet here is to do a quick removal of that first slash (which will also prevent double slash from the base URL and the image URL path).
Uri posterbuiltUri = Uri.parse("http://image.tmdb.org/t/p/w185/").buildUpon()
.appendPath(movieposter.replace("/","").build();
You have an extra '/' in there, encode this instead:
http://image.tmdb.org/t/p/w185/qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
I have a redirect uri of the form https://stackexchange.com/oauth/login_success#access_token=token&expires=5678. I am trying to get the acces token from this url. tried following methods
uri.getQueryParameter("access_token"); //will return null since it is not a query param
uri.getFragment(); //will return "access_token=token&expires=5678" so i need to seperate it again.
Any direct methods? Pls help
Some one might find this helpful
String queryAfterFragment = uri.getFragment();
String dummy_url = "http://localhost?" + queryAfterFragment;
Uri dummy_uri = Uri.parse(dummy_url);
String access_token = dummy_uri.getQueryParameter("access_token");
Works like a charm and easy to use, thank me later :-)
Simple and elegant solution which can get the values which you want:
public static Map<String, String> parseUrlFragment (String url) {
Map<String, String> output = new LinkedHashMap<> ();
String[] keys = url.split ("&");
for (String key : keys) {
String[] values = key.split ("=");
output.put (values[0], (values.length > 1 ? values[1] : ""));
}
return output;
}
It's using LinkedHashMap to represent values, so it's output:
Map<String, String> data = parseUrlFragment (uri.getFragment ());
data.get ("access_token") // token
data.get ("expires") // 5678
You can try in this way
String str = "https://stackexchange.com/oauth/
login_success#access_token=token&expires=5678";
int indexOfHash = str.indexOf("#");
// now you can substring from this
String subStr = str.substring(indexOfHash+1, str.length());
System.out.println(subStr);
// now you can substring from &
String sStr=subStr.substring(0,subStr.indexOf("&"));
System.out.println(sStr);
// now you can get token
String[] arr=sStr.split("=");
System.out.println(arr[0]);
System.out.println(arr[1]);
Out put
access_token=token&expires=5678
access_token=token
access_token
token
You could use the String method split(String) with Regex
str.split("#|&|=")
this splits the string by the passed 3 chars and you get an array with all the splitted parts.
String s =
"https://stackexchange.com/oauth/login_success#access_token=token&expires=5678";
final String[] split = s.split("#|&|=");
for (String s1 : split) {
System.out.println(s1);
}
Output:
https://stackexchange.com/oauth/login_success
access_token
token
expires
5678
I want to check if an url is valid youtube url so that I can shown in view otherwise I will hide the view.
Is there any regular expression in Java that can help me to check if url is valid. Currently I am using this regex but I guess it's not the one I want:
String youTubeURl = "https://www.youtube.com/watch?v=Btr8uOU0BkI";
String pattern = "https?:\\/\\/(?:[0-9A-Z-]+\\.)?(?:youtu\\.be\\/|youtube\\.com\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w]*(?:['\"][^<>]*>|<\\/a>))[?=&+%\\w]*";
if (!youTubeURl.isEmpty() && youTubeURl.matches(pattern)) {
/// Valid youtube URL
}
else{
// Not Valid youtube URL
}
This works for me.
public static boolean isYoutubeUrl(String youTubeURl)
{
boolean success;
String pattern = "^(http(s)?:\\/\\/)?((w){3}.)?youtu(be|.be)?(\\.com)?\\/.+";
if (!youTubeURl.isEmpty() && youTubeURl.matches(pattern))
{
success = true;
}
else
{
// Not Valid youtube URL
success = false;
}
return success;
}
If you want to retrieve the Youtube videoId you can use the following function.
public static String getVideoIdFromYoutubeUrl(String youtubeUrl)
{
/*
Possibile Youtube urls.
http://www.youtube.com/watch?v=WK0YhfKqdaI
http://www.youtube.com/embed/WK0YhfKqdaI
http://www.youtube.com/v/WK0YhfKqdaI
http://www.youtube-nocookie.com/v/WK0YhfKqdaI?version=3&hl=en_US&rel=0
http://www.youtube.com/watch?v=WK0YhfKqdaI
http://www.youtube.com/watch?feature=player_embedded&v=WK0YhfKqdaI
http://www.youtube.com/e/WK0YhfKqdaI
http://youtu.be/WK0YhfKqdaI
*/
String pattern = "(?<=watch\\?v=|/videos/|embed\\/|youtu.be\\/|\\/v\\/|\\/e\\/|watch\\?v%3D|watch\\?feature=player_embedded&v=|%2Fvideos%2F|embed%\u200C\u200B2F|youtu.be%2F|%2Fv%2F)[^#\\&\\?\\n]*";
Pattern compiledPattern = Pattern.compile(pattern);
//url is youtube url for which you want to extract the id.
Matcher matcher = compiledPattern.matcher(youtubeUrl);
if (matcher.find()) {
return matcher.group();
}
return null;
}
You should use
Patterns.WEB_URL.matcher(youTubeURl).matches()
It will return True if URL is valid and false if URL is invalid.
Use android.webkit.URLUtil.isValidUrl(java.lang.String) to check if url is valid. And then you can check if url contains Youtube string.
Like
private boolean isValidUrl(String url) {
if (url == null) {
return false;
}
if (URLUtil.isValidUrl(url)) {
// Check host of url if youtube exists
Uri uri = Uri.parse(url);
if ("www.youtube.com".equals(uri.getHost())) {
return true;
}
// Other way You can check into url also like
//if (url.startsWith("https://www.youtube.com/")) {
//return true;
//}
}
// In other any case
return false;
}
In order to achieve what you want you should use this Regex like so:
private static final Pattern youtubePattern = Pattern.compile("^(http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+");
private boolean isValid = youtubePattern.matcher(youtubeUrl).matches();
where youtubeUrl can be any URL of the following list:
http://youtu.be/t-ZRX8984sc
http://youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=t-ZRX8984sc
http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
https://www.youtube.com/channel/UCDZkgJZDyUnqwB070OyP72g
youtube.com/n17B_uFF4cA
youtube.com/iwGFalTRHDA
http://youtu.be/n17B_uFF4cA
https://youtube.com/iwGFalTRHDA
https://youtube.com/channel/UCDZkgJZDyUnqwB070OyP72g
This regex can match any types of URLs related to youtube.com
This doesn't check if URL is valid or not. It only checks for strings "youtube" & "youtu.be" in your URL. Following is the regex
String yourUrl = "https://youtu.be/Xh0-x1RFEOY";
yourUrl.matches(".*(youtube|youtu.be).*")
" .* " at beginning & end means that there could be anything on left & right of the expression(youtube & youtu.be) you are checking.
NOTE: This has nothing to do with the validity of the URL
My Question: It's very specific. I'm trying to think of the easiest way to parse the following text:
^^domain=domain_value^^version=version_value^^account_type=account_type_value^^username=username_value^^password=password_value^^type=type_value^^location=location_value^^id=xxx^^cuid=cuid_value^^
It will appear exactly like that every time. A few requirements:
Not all of those key-value pairs will appear every time.
They may be in a different order
I'm looking for code something like this:
private String[] getKeyValueInfo(String allStuff) {
String domain = someAwesomeMethod("domain", allStuff);
String version = someAwesomeMethod("version", allStuff);
String account_type = someAwesomeMethod("account_type", allStuff);
String username = someAwesomeMethod("username", allStuff);
String password = someAwesomeMethod("password", allStuff);
String type = someAwesomeMethod("password", allStuff);
String location = someAwesomeMethod("location", allStuff);
String id = someAwesomeMethod("id", allStuff);
String cuid = someAwesomeMethod("cuid", allStuff);
return new String[] {domain, version, account_type, username, password, type, location, id, cuid};
}
What I don't know is what someAwesomeMethod(String key, String allStuff) should contain.
What I was thinking: Something like this:
private String someAwesomeMethod(String key, String allStuff) {
Pattern patt = Pattern.compile("(?i)^^" + key + "=(.*?)^^", Pattern.DOTALL);
Matcher matcher = patt.matcher(allStuff);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
What's wrong with that:
I'm worried it'd be a little slow/cumbersome if I had to do this a lot. So I'm looking for any tips/suggestions.
If you have to do it a lot, i'd make a map, something along the lines of
Map<String, String> m = new HashMap<String, String>();
for (String s : stuff.split("\\^\\^")) // caret needs escaping
{
String[] kv = s.split("=");
m.put(kv[0]) = kv[1];
}
then to lookup a key you'd just do m.get("key")
String.split() will work for that
strVar = /* Your big long string */
String[] vars = strVar.split("\\^\\^"); // needs escaping
I have a String containing a URL. I want to get just one piece of data out of it: an int that should be showing up in the query string.
So if the url is:
http://domain.tld/page.html?iVar=123
I want to get "123" into an int.
What's the most elegant way you know to do this?
You could try matching just that parameter in the URL string:
public static Integer getIVarParamValue(String urlStr) {
Pattern p = Pattern.compile("iVar=(\\d+)");
Matcher m = p.matcher(urlStr);
if (m.find()) {
return Integer.parseInt(m.group(1));
}
return null;
}
It seems you want to obtain get parameters and parse them. I have this method here (got it from somewhere on SO, I guess):
public static Map<String, List<String>> getQueryParams(String url) {
try {
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
}
return params;
} catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
So:
String var = WebUtils.getQueryParams(url).get("iVar");
int intVar = Integer.parseInt(var);
You can use the URL class.
i.e.:
URL myUrl = new URL("http://domain.tld/page.html?iVar=123");
String query = myUrl.getQuery(); //this will return iVar=123
//at this point you can either parse it manually (i.e. use some of the regexp in the other suggestions, or use something like:
String[] parts = query.split();
String variable = parts[0];
String value = parts[1];
This will work only for this case though and won't work if you have additional params or no params.
There are a number of solution that will split it into a param map online, you can see some here.
If it's really as simple as you describe: There is only 1 int in your URL and all you want is that int, I'd go for a regular expression. If it is actually more complicated see the other answers.
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher("http://domain.tld/page.html?iVar=123");
if (m.find())
System.out.println(m.group());
This also could do the work :
public static int getIntParam(HttpServletRequest request, String name, int defaultValue) {
String value = request.getParameter(name);
try {
if (value != null) {
return Integer.valueOf(value);
}
} catch (NumberFormatException e) {
}
return defaultValue;
}
Hope it helps!
If the query string part of the URL is always the same (so if it was always iVar) you could use urlAsString.indexOf("iVar=") to find iVar= and then knowing the number is after that, extract the number. That is admittedly not the least brittle approach.
But if you're looking for all the query strings then Bozho's answer is much better.