![](/img/trans.png)
[英]How to pull url file extension out of url string using javascript
[英]JavaScript: How to pull out a string from a URL using a regular expression
在java中,我將此URL作為字符串:
window.location.href =
"http://localhost:8080/bladdey/shop/c6c8262a-bfd0-4ea3-aa6e-d466a28f875/hired-3";
我想創建一個JavaScript正則表達式以提取以下字符串:
c6c8262a-bfd0-4ea3-aa6e-d466a28f875
為了找到文本的左手標記,我可以使用正則表達式:
window\.location\.href \= \"http\:\/\/localhost:8080\/bladdey\/shop\/
但是,我不知道該如何找到和/hired3"
之間的文本/hired3"
使用JavaScript從URL提取字符串的最佳方法是什么?
你可以在標記分割字符串,並尋找有4個出現的字符串-
或者,如果基數始終相同,則可以使用以下代碼:
String myString = window.location.href;
myString = myString.substring("http://localhost:8080/bladdey/shop/".Length());
myString = myString.subString(0, myString.indexOf('/'));
您可以使用捕獲組來提取字符串的某些內容。 在您的情況下:
Pattern pattern = Pattern.compile("(http://localhost:8080/bladdey/shop/)(.+)(/hired-3)");
Matcher matcher = pattern.matcher(string);
if(matcher.matches()){
String value = matcher.group(2);
}
您需要一個正則表達式,以及使用它的某種方式...
String theLocation = "http://localhost:8080/bladdey/shop/c6c8262a-bfd0-4ea3-aa6e-d466a28f8752/hired-3";
String pattern = "(?</bladdey/shop/).+?(?=/hired3)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
注意-更改主機后,它仍然可以工作(它只會查找bladdey/shop/
)
String param = html.replaceFist("(?s)^.*http://localhost:8080/bladdey/shop/([^/]+)/hired-3.*$", "$1");
if (param.equals(html)) {
throw new IllegalStateException("Not found");
}
UUID uuid = new UUID(param);
在正則表達式中:
(?s)
讓.
char通配符還匹配換行符。 ^
文字開頭 $
文字結尾 .*
零個或多個(*)任何(。)個字符 [^...]+
一個或多個(+)字符而不是(^)是... 在第一個括號之間替換$1
。
好吧,如果您想從任何東西中提取GUID:
var regex = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{11,12}/i
它的確應該為{12}
但在您的url中格式錯誤,並且僅包含15.5字節的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.