![](/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.