1
Pattern.compile("((http\\://|https\\://|ftp\\://|sftp\\://)|(www.))+((\\S+):(\\S+)@)?+(([a-zA-Z0-9\\.-]+\\.[a-zA-Z]{2,4})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(/[a-zA-Z0-9%:/-_\\?\\.'~]*)?");

I have this pattern, I'd like to test if there is a link in my string. I'd like to linkify those text in a TextView.

The code does not work when the link contains a & character.

full code:

Pattern httpMatcher = Pattern.compile("((http\\://|https\\://|ftp\\://|sftp\\://)|(www.))+((\\S+):(\\S+)@)?+(([a-zA-Z0-9\\.-]+\\.[a-zA-Z]{2,4})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(/[a-zA-Z0-9%:/-_\\?\\.'~]*)?");
String httpViewURL  = "myhttp://"; 
Linkify.addLinks(label, httpMatcher, httpViewURL);
1
  • 2
    Not works? What does not work? If you want us to help you, you better give us all the details. Commented Jan 14, 2013 at 21:05

3 Answers 3

5

I think this is cleaner that using regex:

boolean isLink(String s) {
  try {
     new URL(s);
     return true;
  } catch (MalformedURLException e) {
     return false;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have to use Pattern in this case, sorry. Because I d like to Linkify those text in a TextView
3

You can use Patterns.WEB_URL:

public boolean isLink(String string) {
    return Patterns.WEB_URL.matcher(string).matches();
}

Note that Patterns class is available only since API level 8, but you can get its source code here https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Patterns.java

Comments

0
Pattern httpMatcher = Pattern.compile("((http\\://|https\\://)|(www.))+((\\S+):(\\S+)@)?+(([a-zA-Z0-9\\.-]+\\.[a-zA-Z]{2,4})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(/[a-zA-Z0-9%&#-:/-_\\?\\.'~]*)?");

this is working now, thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.