0

文字列 urlString="http://myApp:8080/new/bin/save/SellerMyPage/WebHome"

上記の文字列に、2 つのスラッシュの間に「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;
        }
4

2 に答える 2

6
Pattern p = Pattern.compile("^.*/([^/]+MyPage)/.*");
Matcher m = pattern.matcher(urlString);
if (m.find()) {
  extractedElement = m.group(1);
}
于 2012-04-05T06:29:19.930 に答える
-1

Patternとクラスで実際の正規表現を使用しMatcher、 を使用しないでくださいString.split。次の正規表現を使用できます (警告: テストされておらず、文字列として使用するためにエスケープされていません):

^.*?([^/]+?MyPage/).*$
于 2012-04-05T06:28:59.903 に答える