簡體   English   中英

如何在Java中使用正則表達式從字符串中提取子字符串?

[英]How can i extract substring from the string using regex in Java?

我有一個字符串xxxxxxxxsrc="/slm/attachment/63338424306/Note.jpg"xxxxxxxx現在,我想從字符串中提取子字符串slm/attachment/63338424306/Note.jpgNote.jpg到變量ie temp1 & temp2.

我該如何在Java中使用正則表達式呢?

注意:63338424306可以是任何隨機編號。 &Note.jpg可以是Note.png或abc.jpg或xxxx.yyy等。

請幫助我使用正則表達式提取這兩個字符串。

您可以使用負向后方來獲取文件名

((?:.(?<!/))+)\"

並在正則表達式下獲取完整路徑

/(.*)\"

樣例代碼

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("/(.*)\"");
    Pattern pattern1 = Pattern.compile("((?:.(?<!/))+)\"");
    String matchString = "/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
    Matcher matcher = pattern.matcher(matchString);
    String fullString = "";
    while (matcher.find()) {
        fullString = matcher.group(1);
    }
    matcher = pattern1.matcher(matchString);
    String fileName = "";
    while (matcher.find()) {
        fileName = matcher.group(1);
    }

    System.out.println(fullString + " " + fileName);
}

根據您的評論,使用下面在我的代碼中聲明的字符串:

請說明您的輸入字符串是否不是這樣或我缺少什么。

public static void main(String[] args) {

    String str = "xxxxxxxxsrc=\"/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
    String url = null;

    // The below pattern will grab string between quotes
    Pattern p = Pattern.compile("\"([^\"]*)\"");
    Matcher m = p.matcher(str);
    while (m.find()) {
        System.out.println(m.group(1));
        url = m.group(1);
    }

    // and this will grab filename from the path(url)
    p = Pattern.compile("(?:.(?<!/))+$");
    m = p.matcher(url);
    while (m.find()) {
        System.out.println(m.group());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM