[英]How can I extract substring from the given url using regex in Android Studio
我正在嘗試從 URL https://www.instagram.com/p/CANseIqFMnf/
中使用正則表達式從 ZE84E30B9390CDB64ZAB6DB2C 中提取CANseIqFMnf
。 請幫助我獲得符合 Android Studio 的正則表達式。
這是我的方法的代碼:
String url = "https://www.instagram.com/p/CANseIqFMnf/";
String REGEX = "/p\//";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(url);
boolean match = matcher.matches();
if (match){
Log.e("success", "start = " + matcher.start() + " end = " + matcher.end() );
}else{
Log.e("failed", "failed");
}
但它給了我失敗的回報!
您只需要在String
中使用replaceAll
方法,無需編譯模式並使事情復雜化:
String input = "https://www.instagram.com/p/CANseIqFMnf/";
String output = input.replaceAll("https://www.instagram.com/p/", "").replaceAll("/", "");
Log.v(TAG, output);
請注意,第一個replaceAll
是刪除url
而第二個replaceAll
是刪除任何斜杠/
Pattern pattern = Pattern.compile("https://www.instagram.com/p/(.*?)/");
Matcher matcher = pattern.matcher("https://www.instagram.com/p/CANseIqFMnf/");
while(matcher.find()) {
System.out.println(matcher.group(1));
}
請注意,如果matcher.find()
返回true
,那么如果您在 REGEX (.*?)
中使用了這樣的修飾符,那么找到的部分將在group(1)
中,並且group(0)
將保存整個正則表達式匹配在您的情況下是整個 url。
可以使用java.nio.file.Paths
API 以更簡單的方式實現不帶正則表達式的替代選項
public class Url {
public static void main(String[] args) {
String url = "https://www.instagram.com/p/CANseIqFMnf/";
String name = java.nio.file.Paths.get(url).getFileName().toString();
System.out.println(name);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.