我正在尝试在TextView
内获取特定值,即Youtube链接。
我想只提取例如TextView
的链接,其中包含“Check this out!(Youtube link here)”。 “检查出来!”需要省略,只获取Youtube链接。 TextView
是用户输入的,因此会有所不同。
有什么建议吗?
答案 0 :(得分:5)
你可以试试这个
You can use regular expression with Patterns.WEB_URL regular expression to find all urls in your text.
答案 1 :(得分:1)
public static String extractYouTubeUrl(String text)
{
String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
Matcher urlMatcher = pattern.matcher(text);
while (urlMatcher.find())
{
String url = text.substring(urlMatcher.start(0),
urlMatcher.end(0))
if(url.contains("youtube.com")
return url;
}
return "";
}
如何使用它:
String stringWithYouTubeUrl = tvWithYouTubeUrl.getText().toString();
String youTubeUrl = extractYouTubeUrl(stringWithYouTubeUrl);
Log.d(TAG, "youTubeUrl is" + youTubeUrl);
希望它有所帮助!!
答案 2 :(得分:0)
你可以尝试一下:
String textViewStr = "Check this out! (Youtube link)";
int pos_1 = textViewStr.indexOf('(');
int pos_2 = textViewStr.indexOf(')');
String result = textViewStr.substring(pos_1+1,pos_2);
System.out.println(result); // print: Youtube link
<强>更新强>:
String textViewStr = "asdf Check this out! https://www.youtube.com/ asdg asfgf https:!!";
String [] arrStr = textViewStr.split(" ");
String regex = "/(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/g";
Pattern p = Pattern.compile(regex,Pattern.DOTALL);
for(int i = 0 ; i < arrStr.length ; ++i){
Matcher m = m = p.matcher(arrStr[i]);
if ( m.matches() )
Log.d("Matcher", "PATTERN MATCHES! " + arrStr[i]);
else
Log.d("MATCHER", "PATTERN DOES NOT MATCH! : " + arrStr[i]);
}
此印刷品:
D/MATCHER: PATTERN DOES NOT MATCH! : asdf
D/MATCHER: PATTERN DOES NOT MATCH! : Check
D/MATCHER: PATTERN DOES NOT MATCH! : this
D/MATCHER: PATTERN DOES NOT MATCH! : out!
D/Matcher: PATTERN MATCHES! https://www.youtube.com/
D/MATCHER: PATTERN DOES NOT MATCH! : asdg
D/MATCHER: PATTERN DOES NOT MATCH! : asfgf
D/MATCHER: PATTERN DOES NOT MATCH! : https:!!s
答案 3 :(得分:0)
YouTube链接语法为https://www.youtube.com/watch?v=<value>
。你真正需要的是v=<value>
。只需搜索整个字符串“watch?
”,如果之后有v=
,则只需取值并从中创建整个网址。