gpt4 book ai didi

java - Android:从字符串值中提取链接

转载 作者:行者123 更新时间:2023-12-02 03:22:05 25 4
gpt4 key购买 nike

我想要来自共享 Intent 的链接。当我通过 Chrome 收到链接时,其格式正确,但有时其他应用程序也会添加文本。

示例:

Chrome:“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);
}
}

最佳答案

下面的方法可以解决这个问题:

//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;
}

关于java - Android:从字符串值中提取链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com