2016-09-13 6 views
0

공유 의도에서 링크를 갖고 싶습니다. 크롬을 통해 링크를 받으면 형식이 올바르지 만 때로는 다른 앱도 텍스트를 추가합니다.Android : 문자열 값에서 링크 추출

예 :

크롬 : "www.recode.net/2016/7/21/12243560/google-machine-learning-comics-play"

트위터 : "얘들 아 체크 아웃 이 링크는 정말 멋지다. https://www.recode.net/2016/7/21/12243560/google-machine-learning-comics-play "

트위터의 경우 모든 컨텍스트를 없애고 링크 만 남기고 싶습니다. 즉, www.recode.net/2016/7/21/12243560/ google-machine-learning-comics-play

참고 : 링크의 형식은 https : // .. (또는) www가 될 수 있습니다. .. (또는) recode.net/... (처음에는 www가 없습니다).

이것을 정정하는 정규식은 무엇입니까?

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_shareintent); 

    // Get intent, action and MIME type 
    Intent intent = getIntent(); 
    String action = intent.getAction(); 
    String type = intent.getType(); 

    if (Intent.ACTION_SEND.equals(action) && type != null) 
    { 
     if ("text/plain".equals(type)) 
     { 
      // Handle text being sent 
      handleSendText(intent); 
     } 
    } 
} 

void handleSendText(Intent intent) 
{ 
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); 
    if (sharedText != null) 
    { 
     // Update UI to reflect text being shared 
     TextView tvShare = (TextView) findViewById(R.id.tvShare); 
     tvShare.setText(sharedText); 
    } 
} 
+0

당신은 하나 이상 포함 된 문자열을 검색 할 수 있습니다를 어쩌면 4 자? (공백없이) –

+0

이 코드는 어떻게 관련이 있습니까?/지금까지 시도한 것은 무엇입니까? – njzk2

답변

0

: "."

//Pull all links from the body for easy retrieval 
public ArrayList<String> pullLinks(String text) 
{ 
    ArrayList<String> links = new ArrayList<String>(); 

    //String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]"; 
    String regex = "\\(?\\b(https?://|www[.]|ftp://)[-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; 
} 
0

문자열에서 특정 패턴을 인식하고 추출 할 수 있습니다.

// Pattern for recognizing a URL, based off RFC 3986 
private static final Pattern urlPattern = Pattern.compile(
     "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)" 
       + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*" 
       + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*[email protected]!:/{};']*)", 
     Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); 

예 :

Matcher matcher = urlPattern.matcher("foo bar http://example.com baz"); 
while (matcher.find()) { 
    int matchStart = matcher.start(1); 
    int matchEnd = matcher.end(); 
    // now you have the offsets of a URL match 
} 

참조 : may be other answers there will be useful to you as well 다음 방법은 트릭 않습니다