2016-09-13 64 views
0

我想從共享意圖鏈接。當我通過chrome接收到鏈接時,它的格式正確,但有時其他應用程序也會添加文本。Android:從字符串中提取鏈接值

實施例:

鉻: 「www.recode.net/2016/7/21/12243560/google-machine-learning-comics-play」

Twitter的:「專家檢查出這個鏈接很酷https://www.recode.net/2016/7/21/12243560/google-machine-learning-comics-play

因此,在Twitter的情況下,我想擺脫所有的上下文,只有鏈接剩餘,即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