0

Title is self-explanatory.

Instead of using:

if (link.contains(".com") || (link.contains(".net") || (link.contains(".org") || (link.contains(".info") || ("etc there are many domain names")) {
    webView.loadUrl("https://www." + link);
} else {
    webView.loadUrl("https://www." + link + ".com");
}

I want to do it this way if possible by declaring the String's values globally.

if (link.contains(domainNames)) {
    webView.loadUrl("https://www." + link);
} else {
    webView.loadUrl("https://www." + link + ".com");
}
Greg
  • 357
  • 1
  • 11
  • 1
    This might help https://stackoverflow.com/questions/27110563/how-can-i-check-if-a-string-has-a-substring-from-a-list – Mark Jul 03 '19 at 21:18
  • It is a bit unclear. You want to check which domain is in specific url without entering domains manually? – Yupi Jul 03 '19 at 21:20

2 Answers2

2

Build a regex with the domain names, then test it, e.g.

private static final Pattern DOMAIN_NAMES = Pattern.compile("\\.(?i:com|net|org|info)$");
if (DOMAIN_NAMES.matcher(link).find()) {
    webView.loadUrl("https://www." + link);
} else {
    webView.loadUrl("https://www." + link + ".com");
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Be warned, this is very error prone if two url endings happen to have mostly matching parts as a regex like e.g. `(a|abc)` will never match `abc` as the first alternatives consumes the `a` only leaving the `bc` to match, which won't happen now! You have to order your endings by length to avoid this issue – roookeee Jul 03 '19 at 21:32
  • 1
    @roookeee You are wrong, since the regex **backtracking** will ensure that `(a|abc)$` will match any string ending in `a` or `abc`. See [regex101](https://regex101.com/r/HJU7Mq/1) for proof. – Andreas Jul 03 '19 at 21:52
  • You are right, when using `$` this doesn't matter. It only matters in cases where one wants to have the most exact match (without using `$` at the end) as seen [here](https://regex101.com/r/gCjPie/1) – roookeee Jul 03 '19 at 22:53
  • This worked great. I use voice input to fill "link", it might be my imagination but i think voice searches are more accurate than before? anyway this is awesome... – Greg Jul 04 '19 at 09:05
0

Another mannual approach could be : Domainnamelist.contains(substring from link that contains domain ending)

Ashok Kumar
  • 1,226
  • 1
  • 10
  • 14