簡體   English   中英

匹配正則表達式Java前后的所有內容

[英]Match everything after and before something regex Java

這是我的代碼:

    String stringToSearch = "https://example.com/excludethis123456/moretext";

    Pattern p = Pattern.compile("(?<=.com\\/excludethis).*\\/"); //search for this pattern 
    Matcher m = p.matcher(stringToSearch); //match pattern in StringToSearch

    String store= "";


    // print match and store match in String Store
    if (m.find())
    {
        String theGroup = m.group(0);
        System.out.format("'%s'\n", theGroup); 
        store = theGroup;
    }

    //repeat the process
    Pattern p1 = Pattern.compile("(.*)[^\\/]");
    Matcher m1 = p1.matcher(store);

    if (m1.find())
    {
        String theGroup = m1.group(0);
        System.out.format("'%s'\n", theGroup);
    }

我想匹配excludethis之后和/之后的所有內容。

使用"(?<=.com\\\\/excludethis).*\\\\/"正則表達式,我將匹配123456/並將其存儲在String store 之后用"(.*)[^\\\\/]"排除/並得到123456

我可以在一行中執行此操作,即將這兩個正則表達式合並嗎? 我不知道如何合並它們。

這可能對您有用:)

String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern pattern = Pattern.compile("excludethis([\\d\\D]+?)/");
Matcher matcher = pattern.matcher(stringToSearch);

if (matcher.find()) {
    String result = matcher.group(1);
    System.out.println(result);
}

就像您使用正面的外觀一樣,您可以使用正面的外觀並將正則表達式更改為此,

(?<=.com/excludethis).*(?=/)

另外,在Java中,您無需轉義/

您修改的代碼,

String stringToSearch = "https://example.com/excludethis123456/moretext";

Pattern p = Pattern.compile("(?<=.com/excludethis).*(?=/)"); // search for this pattern
Matcher m = p.matcher(stringToSearch); // match pattern in StringToSearch

String store = "";

// print match and store match in String Store
if (m.find()) {
    String theGroup = m.group(0);
    System.out.format("'%s'\n", theGroup);
    store = theGroup;
}
System.out.println("Store: " + store);

打印,

'123456'
Store: 123456

就像您想抓住價值一樣。

如果您不想使用regexregex可以嘗試使用String::substring *

String stringToSearch = "https://example.com/excludethis123456/moretext";
String exclusion = "excludethis";
System.out.println(stringToSearch.substring(stringToSearch.indexOf(exclusion)).substring(exclusion.length(), stringToSearch.substring(stringToSearch.indexOf(exclusion)).indexOf("/")));

輸出:

123456

* 絕對不要實際使用

暫無
暫無

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

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