String urlString =“http:// myApp:8080 / new / bin / save / SellerMyPage / WebHome”
我想检查上面的字符串是否包含两个正斜杠之间的字符串“MyPage”。它也应该在斜杠之间,并且应该是前缀 有一些人物。这是我期待的结果
"http://myApp:8080/new/bin/save/SellerMyPage/WebHome" should return true
"http://myApp:8080/new/bin/save/SellerMyPage1/WebHome" should return false(its not ending with MyPage)
"http://myApp:8080/new/bin/save/MyPage/WebHome" should return false(MyPage is not prefixed with any any character)
看起来我需要采取相同的正则表达式?如果有人可以帮我解决正则表达式,我将不胜感激?
如果它包含,我想在第一种情况下提取该字符串,它应该返回SellerMyPage
为了提取我在下面的代码片段使用的部分,但对我来说,我不相信它是优化的方式。我相信应该有比这更好的方法吗?
String extractedElement="";
String[] urlSpliArray=urlString.split("/");
for(String urlElement:urlSpliArray)
if(urlElement.endsWith("MyPage"))
{
extractedElement=urlElement;
}
答案 0 :(得分:6)
Pattern p = Pattern.compile("^.*/([^/]+MyPage)/.*");
Matcher m = pattern.matcher(urlString);
if (m.find()) {
extractedElement = m.group(1);
}
答案 1 :(得分:-1)
对Pattern
和Matcher
类使用真正的正则表达式,不要使用String.split
。您可以使用以下正则表达式(警告:未测试且未转义以用作字符串):
^.*?([^/]+?MyPage/).*$